美文网首页
iOS UICollectionView received la

iOS UICollectionView received la

作者: MQ_Twist | 来源:发表于2021-03-25 14:53 被阅读0次

人人有自己的位置,忘乎所以,就危险了。

前言

昨天版本提测,又到了可以写文章的时间了,想啥来啥,今天早上刚到公司就看到有几个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方法,貌似reloadSectionsreloadData更快。

情景二

项目中有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有大动作,哪位大佬有相关文章给一下,不胜感激。

相关文章

网友评论

      本文标题:iOS UICollectionView received la

      本文链接:https://www.haomeiwen.com/subject/jinlhltx.html