iOS collectionView 布局崩溃问题

今天遇到collectionView 刷新的时候崩溃的问题,以此来记录一下解决方法。
这种崩溃有两种报错,分别是*** Assertion failure in -[UICollectionViewData validateLayoutInRect:] 和 [UICollectionView received layout attributes for a cell with an index path that does not exist]

产生这种崩溃的根源是collectionView reloadData时,数据源已经变了,但是cell的layout attributes还没有更新,也就是collectionViewLayout出了故障

解决方案有一下几种

1.reload之前调整布局(对我有效)

[self setNeedsLayout];

2.(对我无效)

-(NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView{

[myCollectionView.collectionViewLayout invalidateLayout];
}

3.关闭iOS 10的新特性UICollectionViewCell的Pre-Fetching预加载(对我无效)

// Swift
if #available(iOS 10, *) {
collectionView.prefetchingEnabled = false
}
//Objective-C
if ([self.collectionView respondsToSelector:@selector(setPrefetchingEnabled:)]) {
self.collectionView.prefetchingEnabled = false;
}

4.第四种方式(未尝试)

你可能感兴趣的:(iOS collectionView 布局崩溃问题)