自定义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: 
 {length = 2, path = 1 - 0}'

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

-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect{

NSMutableArray *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,

你可能感兴趣的:(自定义UICollectionView : received layout attributes for a cell with an index path that does not exist)