iOS UICollectionView received la

2021-03-25  本文已影响0人  MQ_Twist

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

前言

昨天版本提测,又到了可以写文章的时间了,想啥来啥,今天早上刚到公司就看到有几个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会重新刷新布局,不会沿用旧的布局导致获取不到数据,导致崩溃。

情景二

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

上一篇 下一篇

猜你喜欢

热点阅读