5

我有一个集合视图(使用组合布局和可区分的数据源),它的标题中有一个分段控件。当控制值发生变化时,单元格会更新为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
        }
4

0 回答 0