You have to create the subclass for your UICollectionViewDiffableDataSource.
final class SectionIndexTitlesCollectionViewDiffableDataSource: UICollectionViewDiffableDataSource<Section, SectionItem> {
private var indexTitles: [String] = []
func setupIndexTitle() {
indexTitles = ["A", "B", "C"]
}
override func indexTitles(for collectionView: UICollectionView) -> [String]? {
indexTitles
}
override func collectionView(_ collectionView: UICollectionView, indexPathForIndexTitle title: String, at index: Int) -> IndexPath {
// your logic how to calculate the correct IndexPath goes here.
guard let index = indexTitles.firstIndex(where: { $0 == title }) else {
return IndexPath(item: 0, section: 0)
}
return IndexPath(item: index, section: 0)
}
}
You can use now this custom diffable data source in your vc instead of regular UICollectionViewDiffableDataSource.
N.B But there is a small trick.
You must have to setup indexTitles once applying snapshot completes, otherwise it may crash.
dataSource?.apply(sectionSnapshot, to: section, animatingDifferences: true, completion: { [weak self] in
self?.dataSource?.setupIndexTitle()
self?.collectionView.reloadData()
})