UICollectionView 与自定义 UICollectionViewLayout validateLayoutInRect accertion

UICollectionView with custom UICollectionViewLayout validateLayoutInRect accertion

我正在创建带有自定义集合视图布局的集合视图的应用程序。一切正常,直到移除一个单元格。 [collectionView reloadData] 之后一切似乎都很好。但是在集合视图滚动后应用程序因断言而崩溃。

Assertion failure in -[UICollectionViewData validateLayoutInRect:]
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UICollectionView received layout attributes for a cell with an index path that does not exist: <NSIndexPath: 0xc000000000060016> {length = 2, path = 0 - 12}

我已经在 Whosebug 上查了很多答案,尝试了很多东西,但仍然无法摆脱这个问题。

带有我的自定义布局的小示例项目和我在此处上传的这个问题:

https://github.com/fizzy871/CollectionViewCustomLayoutBugFix

有集合视图和 "remove cell" 按钮可以删除最后一个单元格并产生崩溃。

拜托,谁知道为什么会这样或者有什么想法,帮我解决这个问题。

你应该覆盖 - finalLayoutAttributesForDisappearingItemAtIndexPath: 并从 layoutAttributes 字典中删除已删除项的属性。

出现断言是因为 collectionView 在最后一个项目之后请求项目的布局属性,并期望从布局中获得 nil 响应,但因为属性仍在您的字典中,所以它们被返回了。

我找出问题所在。我对具有属性的字典使用延迟加载,并且在布局无效后新属性被添加到字典中。更早的元素也在这里。现在在 prepareLayout 中删除了字典,一切正常。

谢谢你,特里斯坦伯恩赛德。你带我走正路。