我在对UICollectionViewDiffableDataSource应用NSDiffableDataSourceSnapshot时遇到了一个问题。想象一下这样的情况:我有两个项目,我想删除第二个项目,还想重新加载该部分中的所有其他项目。
我是这样做的:
var snapshot = oldSnapshot
if let item = getterForItemToDelete() {
snapshot.deleteItems([item])
}
snapshot.reloadItems(otherItems)但是,在数据源的单元格提供者中,应用程序崩溃,因为它试图获取项目标识符的单元格,而我不再有数据,所以我必须返回nil
let dataSource = MyDataSource(collectionView: collectionView) { [weak self] collectionView, indexPath, identifier in
guard let viewModel = self?.viewModel.item(for: identifier) else { return nil }
...
}奇怪的是,当我尝试调试它并在应用快照时打印我的项目时,它打印了一项:
(lldb) print snapshot.itemIdentifiers(inSection: .mySection)
([App.MyItemIdentifier]) $R0 = 1 value {
[0] = item (item = "id")
}但是,在这之后,在cell provider中,我得到了两个项目,但我没有
(lldb) print self?.dataSource.snapshot().itemIdentifiers(inSection: .mySection)
([App.MyItemIdentifier]) $R1 = 2 values {
[0] = item (item = "ckufpa58100041ps6gmiu5zl6")
[1] = item (item = "ckufpa58100051ps69yrgaspv")
}更奇怪的是,当我有3个项目,并且我想删除其中一个并重新加载其他项目时,这种情况不会发生。
解决我的问题的一个解决方法是在单元提供程序中返回空单元格而不是nil:
let dataSource = MyDataSource(collectionView: collectionView) { [weak self] collectionView, indexPath, identifier in
guard let viewModel = self?.viewModel.item(for: identifier) else {
return collectionView.dequeueReusableCell(withReuseIdentifier: "UICollectionViewCell", for: indexPath)
}
...
}最后一件奇怪的事情是,当我这样做,然后我查看View Hierarchy调试器时,只有一个单元格,所以看起来空单元格被删除了。
有没有人知道我会做错什么,或者这只是预期的行为?因为我在文档中没有发现任何关于为一些优化、动画或其他东西提供单元的内容。
发布于 2021-10-10 06:08:09
您不应该从快照中删除项目。将它们从数组中删除。使用更新后的阵列再次创建dataSource,并使用此新创建的dataSource调用快照。CollectionView将使用新数据自动更新。更简单地说,更改数组,然后再次使用applySnapshot()。
https://stackoverflow.com/questions/69494230
复制相似问题