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

0

10

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
        }
Bloodstained answered 14/5, 2021 at 19:4 Comment(2)
Did you find a solution for this. I am facing same issueAday
Did you find any solution?Tarttan

© 2022 - 2024 — McMap. All rights reserved.