当我使用UICollectionView并设置了UICollectionViewFlowLayout。然后尝试通过以下方式应用数据源的快照
// load initial data
reloadDataSource()
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3)) {
self.reloadDataSource(animating: true)
}
我在延迟3秒后应用第二个快照时出现崩溃。崩溃只发生在动画制作时:true。
如果我把animating设置为false,那么就不会崩溃,但集合视图如果留空。
下面是这个应用数据源的方法
extension CollectionViewController {
func reloadDataSource(animating: Bool = false) {
print("reloading data source with snapshot -> \(snapshot.numberOfItems)")
self.dataSource.apply(self.snapshot, animatingDifferences: animating) {
print("applying snapshot completed!")
}
}
}
数据源只是
let dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView, cellProvider: cellProvider)
你可以玩的完整项目(可能会随着时间的推移而改变)。https:/github.comichzioSwifUICollectionView。
更新
我试着简化例子,做一些类似的事情,但它不能正常工作。似乎将.apply()移动到后台队列,其他队列会导致集合视图中的数据为空。
func reloadDataSource(animating: Bool = false) {
print("reloading data source with snapshot -> \(snapshot.numberOfItems)")
diffQueue.async {
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.categories])
snapshot.appendItems(Item.categoryItems)
self.dataSource.apply(snapshot, animatingDifferences: animating) {
print("applying snapshot completed!")
}
}
}
好吧,我似乎找到了通过应用新的快照更新数据源的所有错误的原因。
这个懒惰的var dataSource会导致错误。
private(set) lazy var dataSource: UICollectionViewDiffableDataSource<Section, Item> = {
let dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView, cellProvider: cellProvider)
//dataSource.supplementaryViewProvider = supplementaryViewProvider
return dataSource
}()
我把它改成了
private(set) var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
在viewDidLoad()中configureCollectionView之后,现在我调用configureDataSource()来做懒惰的var初始化器中的事情。