swiftuicollectionviewsnapshotdiffabledatasourceuicollectionviewdiffabledatasource

Swift Diffable Snapshot - Add new Section to Snapshot and Reload Collection View


I have a collection view that has sections and the beginning. I want to add a new section after the user creates data and display data in the new section. Here is the code I have tried but failed. The new section does not appear after running the code.

var snapshot = self.collectionView.diffableDataSource.snapshot()

let recentlySection = Section(title: "Recently Colored",
                                      cells: [userPicture],
                                      sectionType: .recentlyColored)
        
snapshot.appendSections([recentlySection])
snapshot.appendItems([userPicture], toSection: recentlySection)

self.collectionView.diffableDataSource.apply(snapshot, animatingDifferences: true)
self.collectionView.reloadData()

Thank you!


Solution

  • I have solved my problem. I am leaving answer here in case of anyone encounters the same problem. I forgot to add new section to my collection view sections list. Adding this line solved my problem.

    self.collectionView.sections.insert(recentlySection, at: 2)