Diffable Data Source Scrolls to Top After Applying Snapshot with All New Data in Collection View

1.3k views Asked by At

I have a collection view (using a compositional layout and a diffable data source) that has a segmented control in its header. When the control value changes, the cells update to a different UICollectionViewCell class with all new data. It mostly works as expected. The issue is that my collection view scrolls back to the top when the I apply my snapshot. How can I keep it from scrolling?

Called when my view loads:

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

Called when the segmented control changes:

    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)
    }

Setting up my Cells and Supplementary view:

        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
        }
0

There are 0 answers