您必须为您的 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)
}
}
你现在可以在你的 vc 中使用这个自定义的 diffable 数据源,而不是常规的 UICollectionViewDiffableDataSource。
NB但有一个小技巧。应用快照完成后,您必须设置 indexTitles,否则可能会崩溃。
dataSource?.apply(sectionSnapshot, to: section, animatingDifferences: true, completion: { [weak self] in
self?.dataSource?.setupIndexTitle()
self?.collectionView.reloadData()
})