自定义UICollectionView : received layout attributes for a cell with an index path that does not exist

最近用UICollectionView做表格控件,自定义UICollectionViewLayout的遇到了一个崩溃。

*** 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}'

在UICollectionViewLayout的重载接口中我们需要定义

-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{

NSMutableArray<UICollectionViewLayoutAttributes *> *layoutAttributes = [NSMutableArray array];
/*计算需要展示的cell*/
/*
UICollectionViewLayoutAttributes
@property(nonatomic, strong) NSIndexPath *indexPath;
*/
return  layoutAttributes;
}

在UICollectionView的delegate接口我们需要实现

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    // return  SectionsNum
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    // return  numberOfSection
}

崩溃的原因:

layoutAttributesForElementsInRect返回的UICollectionViewLayoutAttributes数组有indexPath没有被 [NSIndexPath indexPathForRow:numberOfSection]覆盖。
换而言之
SectionsNum不小于layoutAttributes中任何一个UICollectionViewLayoutAttributes的indexPath.section,
numberOfSection不小于layoutAttributes中任何一个UICollectionViewLayoutAttributes的indexPath.item,

    原文作者:氮化镓加砷
    原文地址: https://www.jianshu.com/p/d3e50ff03c2d
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞