自定义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,

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容