【问题标题】:Is applying NSDiffableDataSourceSnapshot broken?应用 NSDiffableDataSourceSnapshot 是否损坏?
【发布时间】:2021-11-28 07:36:21
【问题描述】:

我在将NSDiffableDataSourceSnapshot 应用到UICollectionViewDiffableDataSource 时遇到问题。想象一下这种情况:我有两个项目,我想删除第二个项目,并且我想重新加载该部分中的所有其他项目。

我是这样做的:

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")
}

但是,在此之后,在单元格提供程序中,我得到了我有两个项目,但我没有

(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 调试器时,只有一个单元格,因此似乎删除了空单元格。

有谁知道我会做错什么,或者这只是预期的行为?因为我没有在文档中找到任何关于为某种优化、动画或其他内容提供单元格的内容。

【问题讨论】:

    标签: swift uicollectionview uicollectionviewdiffabledatasource nsdiffabledatasourcesnapshot


    【解决方案1】:

    您不应该从快照中删除项目。从您的阵列中删除它们。使用更新后的数组再次创建数据源,并使用这个新创建的数据源调用快照。 CollectionView 将使用新数据自动更新。更简单的说,改变数组,然后再次applySnapshot()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-13
      • 1970-01-01
      • 2011-01-28
      • 2013-12-02
      • 2011-02-15
      • 1970-01-01
      • 2011-10-02
      • 2010-09-08
      相关资源
      最近更新 更多