人人有自己的位置,忘乎所以,就危险了。
前言
昨天版本提测,又到了可以写文章的时间了,想啥来啥,今天早上刚到公司就看到有几个bug在那躺着,而且还有一个有趣的,切入正题。
正文
该bug是在特定机型会导致闪退,必现,目前确定iOS 13
以下必现。拿到手机后发现崩在main函数里面,错误提示是:
reason: 'UICollectionView received layout attributes for a cell with an index path that does not exist:
<NSIndexPath: 0x9b978cb9f82b3618> {length = 2, path = 0 - 0}'
意思很明显,就是UICollectionViewCell
在布局的时候数据越界,有点懵逼,先上解决方法。
情景一
查看代码中在reloadData
函数之前有没有对数据进行删除操作,若有:
- 方法一
[self.collectionView reloadData];
[self.collectionView.collectionViewLayout invalidateLayout];
在reloadData
之后将当前的布局设置失效invalidateLayout
,则collectionView
会重新刷新布局,不会沿用旧的布局导致获取不到数据,导致崩溃。
- 方法二
使用reloadSections
方法,貌似reloadSections
比reloadData
更快。
情景二
项目中有UICollectionViewFlowLayout
的子类,重写了- (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
- (NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
//获取到父类所返回的数组(里面放的是当前屏幕所能展示的item的结构信息)
NSArray *superAttrs = [super layoutAttributesForElementsInRect:rect];
if (superAttrs.count == 0) {//不加这个话,在iOS 13 以下会creash
return superAttrs;
}
UICollectionViewLayoutAttributes *attri = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:self.index inSection:0]];
}
后记
记得好像iOS 13
之后苹果对UICollectionView
有大动作,哪位大佬有相关文章给一下,不胜感激。
网友评论