在集合视图中使用所有新数据应用快照后,Diffable 数据源滚动到顶部

问题描述

我有一个集合视图(使用组合布局和可区分的数据源),其标题中有一个分段控件。当控件值更改时,单元格会更新为包含所有新数据的不同 UICollectionViewCell 类。它主要按预期工作。问题是当我应用我的快照时,我的集合视图会滚动回顶部。我怎样才能让它不滚动?

在我的视图加载时调用

    func initialDataSourceSetUp() {
        var snapshot = NSDiffableDataSourceSnapshot<Section,SampleDataObject>()
        snapshot.appendSections([.main])
        snapshot.appendItems(sampleData)
        sampleDataSource.apply(snapshot,animatingDifferences: true,completion: nil)
    }

分段控件改变时调用

    func updateDataSource() {
        var snapshotSectionMain = sampleDataSource.snapshot(for: .main)
        snapshotSectionMain.deleteall()
        if currentSegment == 0 {
            snapshotSectionMain.append(sampleData)
        } else {
            snapshotSectionMain.append(sampleData2)
        }
        sampleDataSource.apply(snapshotSectionMain,to: .main)
    }

设置我的单元格和补充视图:

        sampleDataSource = UICollectionViewDiffableDataSource(collectionView: collectionView,cellProvider: { (collectionView,indexPath,item) -> UICollectionViewCell? in
            if self.currentSegment == 0 {
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: BasicRentalItemCollectionViewCell.identifier,for: indexPath) as! BasicRentalItemCollectionViewCell
                cell.imageMain.image = item.image
                cell.labelTitle.text = item.title
                return cell
            } else {
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CustomerReviewCollectionViewCell.identifier,for: indexPath) as! CustomerReviewCollectionViewCell
                cell.labelTitle.text = item.title
                cell.imageViewAvatar.image = item.image
                return cell
            }
        })
        
        sampleDataSource.supplementaryViewProvider = { collectionView,kind,indexPath in
            guard kind == UICollectionView.elementKindSectionHeader else {
                return nil
            }

            let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind,withReuseIdentifier: ProfileHeaderView.identifier,for: indexPath) as! ProfileHeaderView

            header.delegate = self
            header.user = self.user
            header.isPersonalProfile = self.isPersonalProfile

            return header
        }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)