How to stop UICollectionViewDiffableDataSource to scroll the collection view while apply snapshot?

334 Views Asked by At

I have a UICollectionViewDiffableDataSource for vertical scrolling, with dynamic height cells.

Every time I call 'apply' on the datasource the collection view scrolls a bit and it doesn't look good. How do I prevent it from scrolling?

private func applySnapshot(completion: @escaping () -> ()) {
    let sections = presenter.getSections().filter({$0.date != nil} ).map({$0.date!})
    var snapshot = Snapshot()
    snapshot.appendSections(sections)
    sections.forEach { (date) in
        if var events = presenter.getEvents(by: date) {
            if events.isEmpty {
                events = [Event(emptyEventDate: date)]
            }
            snapshot.appendItems(events, toSection: date)
        }
    }
    self.dataSource.apply(snapshot, animatingDifferences: false) {
        completion()
    }
}


private func createLayout() -> UICollectionViewLayout {
    let kHeaderHeight: CGFloat = 25
    let kSectionInsetTop: CGFloat = 8
    let kSectionInsetLeadingTrailing: CGFloat = 15
    let kSectionInsetBottom: CGFloat = 28
    let kItemSpacing: CGFloat = 12

    let estimatedHeight = CGFloat(400)
    let layoutSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
                                            heightDimension: .estimated(estimatedHeight))
    
    let item = NSCollectionLayoutItem(layoutSize: layoutSize)
    let group = NSCollectionLayoutGroup.horizontal(layoutSize: layoutSize,
                                                   subitem: item,
                                                   count: 1)
    group.contentInsets = NSDirectionalEdgeInsets(
        top: 0,
        leading: kSectionInsetLeadingTrailing,
        bottom: 0,
        trailing: kSectionInsetLeadingTrailing)
    let section = NSCollectionLayoutSection(group: group)
    section.contentInsets = NSDirectionalEdgeInsets(
        top: kSectionInsetTop,
        leading: 0,
        bottom: kSectionInsetBottom,
        trailing: 0)

    section.interGroupSpacing = kItemSpacing
    let headerSize = NSCollectionLayoutSize(
        widthDimension: .fractionalWidth(1.0),
        heightDimension: .absolute(kHeaderHeight)
    )
    let sectionHeader = NSCollectionLayoutBoundarySupplementaryItem(
        layoutSize: headerSize,
        elementKind: UICollectionView.elementKindSectionHeader,
        alignment: .top
    )
    
    sectionHeader.pinToVisibleBounds = true
    section.boundarySupplementaryItems = [sectionHeader]
    let layout = UICollectionViewCompositionalLayout(section: section)

    return layout
}

I appreciate your help

  • Edit: I see that the view "jumps"/scrolls a bit when I insert a new item/section before the visible cells. If I insert after it doesn't happen.
0

There are 0 best solutions below