UICollectionView reloadData Crash 解决方案

问题

UICollectionView如果更新datasource,需要更新UI,直接使用

[self.datas removeAllObjects];
[UICollecitonView reloadData];

就会直接崩溃。

崩溃log

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UICollectionView received layout attributes for a cell with an index path that does not exist: <NSIndexPath: 0xc000000000000116> {length = 2, path = 1 - 0}'
*** First throw call stack:
(0x1824a2fe0 0x180f04538 0x1824a2eb4 0x182f3a720 0x188630a9c 0x18862fe90 0x18862f388 0x1885d107c 0x1857c1274 0x1857b5de8 0x1857b5ca8 0x18573134c 0x1857583ac 0x188852524 0x188dc89f8 0x188dc8b9c 0x18245142c 0x182450d9c 0x18244e9a8 0x18237eda4 0x183de8074 0x188639058 0x10010dd58 0x18138d59c)
libc++abi.dylib: terminating with uncaught exception of type NSException

解决方案

[self.collectionView reloadData];
[self.collectionView.collectionViewLayout invalidateLayout];

在reloadData之后将当前的布局设置失效invalidateLayout,则collectionView会重新刷新布局,不会沿用旧的布局导致获取不到数据,导致崩溃。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容