自定义UICollectionView : received l

2018-04-04  本文已影响805人  氮化镓加砷

最近用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,

上一篇下一篇

猜你喜欢

热点阅读