ios - 使用自定义布局重新加载 UICollectionView 会引发错误

标签 ios swift uicollectionview uicollectionviewlayout

我正在尝试使用此 tutorial 在我的 UICollectionView 上实现 Apple Watch 动画。 它有一个单独的 UICollectionViewLayout 类用​​于所需的布局。

我将元素放入数组中,当我必须使用我过去调用的新值更新 Collection View 时

self.collectionView.reloadData()

但它引发了我以下错误

*** Assertion failure in -[UICollectionViewData validateLayoutInRect:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit/UIKit-3600.8.1/UICollectionViewData.m:433

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UICollectionView received layout attributes for a cell with an index path that does not exist: <NSIndexPath: 0x170222520> {length = 2, path = 0 - 1}'

然后我用了

self.collectionView.collectionViewLayout.invalidateLayout()

在重新加载之前使布局无效。但我的代码仍然抛出之前的错误。所以我尝试重新加载部分:

let indexSet = IndexSet(integer: 0)
self.collectionView.reloadSections(indexSet)

这一次,布局有时无法正确显示。它有一个扭曲的 UI,有时会在以下代码行上抛出 EXC_BAD_ACCESS 错误:

 self.collectionView.collectionViewLayout = layout // error comes on this line

有什么解决办法吗?请查看上面提到的教程来理解我的代码。我引用了很多答案,但无法解决这个问题。

最佳答案

问题是因为即使数据为nil,您也会返回UICollectionViewLayoutAttributes,因此出现错误:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UICollectionView received layout attributes for a cell with an index path that does not exist: <NSIndexPath: 0x170222520> {length = 2, path = 0 - 1}'

tutorial ,方法layoutAttributesForItemAtIndexPath ,它返回属性,正在从 layoutAttributesForElementsInRect 调用其中cellCountcellCount = ROWS * COLS

假设您可能已更改 numberOfItemsInSection要反射(reflect)您的数据,您必须更改 cellCount 的条件也是。

关于ios - 使用自定义布局重新加载 UICollectionView 会引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44278538/

相关文章:

ios - CocoaPods 在添加新 pod 时出现问题

swift - 快速将图像从一个 View Controller 传递到另一个 View Controller

ios - 在 Swift 中存储一个没有初始化的对象

swift - 如何使用分页设置水平 UICollectionView,但每页的项目从左到右和从上到下排列

ios - 水平滚动集合查看问题

ios - 水平方向自动移动 UICollectionCells

ios - 取消 UITextView 中的选择/粘贴菜单?

ios - 在 iPhone 上拍照而不显示控件

ios - 带有递减迭代器的 Swift 2.2 for 循环

ios - 添加到 sharedApplication 的 keyWindow 时,UIView 未注册触摸事件