在Swift中捕获UICollectionView执行批量更新断言失败?

6
我正在使用UICollectionView的performBatchUpdates(_:completion:)方法。问题在于,有时我的复杂差异逻辑会失败并返回一个不正确的插入节的数量。这导致我插入的项目数与数据源报告的数量不匹配。每当发生这种情况时,我们会收到以下错误:

Assertion failure in -[CollectionView _endItemAnimationsWithInvalidationContext:tentativelyForReordering:animator:]

Error when performing batch updates: Invalid update: invalid number of sections. The number of sections contained in the collection view after the update (25) must be equal to the number of sections contained in the collection view before the update (19), plus or minus the number of sections inserted or deleted (0 inserted, 0 deleted).

我意识到正确的解决方案是修复我的差异逻辑,使返回的项目数与我调用的插入数不相冲突。
然而,我的目标是,即使我的逻辑在未来失败,也不会使应用崩溃,而是重新加载集合视图的数据。

我该如何在Swift中实现这个?

1个回答

5

默认情况下,Swift无法捕获NSExceptions异常,因此需要创建类似于这个这个的桥接。

即使您捕获了断言失败,用户也无法与集合视图进行交互,因此您需要重新创建集合视图。

TryCatch.try({
  collectionView.performBatchUpdates({
    collectionView.insertItems(at: indexPaths)
    collectionView.insertSections(sections)
  }, completion: nil)
}, catch: { exception in
  print("Error updating collection view: \(exception)")

  collectionView.removeFromSuperview()

  // recreate the collection view (make sure to set datasource and delegates)
  collectionView = ...
  collectionView.dataSource = ...
  collectionView.delegate = ...
}, finally: nil)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接