TOPCOD3R
TOPCOD3R

Reputation: 154

How to reload data in section in UICollectionView when using UICollectionViewDiffableDataSource?

I am using UICollectionViewDiffableDataSource for my collectionView's data source. I have 3 sections in my CollectionView:

enum Section {
    case section1
    case section2
    case section3
}

Initially, I am appending these 3 sections to the collectionView using the following code:

var snapshot = self.diffableDataSource.snapshot()
snapshot.appendSections([.section1, .section2, .section3])
self.diffableDataSource.apply(snapshot)

I then append items to the sections using the following code:

var snapshot = self.diffableDataSource.snapshot()
snapshot.appendItems([myItems], toSection: .section1)
self.diffableDataSource.apply(snapshot)

My problem is that I cannot figure out how to reload a section in the collection view with a new set of items without appending them to the current ones. The methods available to the snapshot only allow for items to be appended to the section, but I need the items of the section to be replaced. I have tried deleting the section, appending it back then appending the new set of items:

snapshot.deleteSections([.section1])
snapshot.appendSections([.section1])
snapshot.appendItems([myItems], toSection: .section1)

This just removes the section but does not load the new items. I am looking for a way to simply refresh the section with the new items, similarly to how you would call collectionView.reloadData() when using the normal UICollectionViewDataSource.

Upvotes: 7

Views: 5449

Answers (1)

vadian
vadian

Reputation: 285220

To modify the snapshot directly

  • Determine the items in that section
  • Delete the items
  • Append the new items
  • Reload the section
  • Apply the snapshot

This is a generic method as extension of UICollectionViewDiffableDataSource

extension UICollectionViewDiffableDataSource {
    
    func replaceItems(_ items : [ItemIdentifierType], in section: SectionIdentifierType) {
        var currentSnapshot = snapshot()
        let itemsOfSection = currentSnapshot.itemIdentifiers(inSection: section)
        currentSnapshot.deleteItems(itemsOfSection)
        currentSnapshot.appendItems(items, toSection: section)
        currentSnapshot.reloadSections([section])
        apply(currentSnapshot, animatingDifferences: true)
    }
}

Please name structs representing the data source with starting uppercase letter and in singular form (MyItem).

Upvotes: 9

Related Questions