我有一个UICollectionView,我将数据输入到使用UICollectionViewDiffableDataSource中。我想在它的后缘显示一个滚动洗涤器,就像实现数据源方法indexTitlesForCollectionView和indexPathForIndexTitle一样。但是数据源是不同的数据源对象,在iOS 15中没有属性或闭包来提供索引标题。
索引标题应该如何与UICollectionViewDiffableDataSource一起工作
发布于 2021-12-15 07:12:07
您必须为您的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中使用这个自定义的可扩展数据源,而不是常规的UICollectionViewDiffableDataSource。
N.B但是有个小把戏。应用快照完成后,必须设置indexTitles,否则可能会崩溃。
dataSource?.apply(sectionSnapshot, to: section, animatingDifferences: true, completion: { [weak self] in
self?.dataSource?.setupIndexTitle()
self?.collectionView.reloadData()
})https://stackoverflow.com/questions/69936255
复制相似问题