UICollectionView收到了一个索引路径不存在的单元格的布局属性

时间:2014-07-16 15:33:20

标签: ios objective-c uicollectionview uicollectionviewcell

我使用了UICollection视图来显示网格布局中的项目。

对于数据源,我使用了5 * 5维数组。

而且我在section中为numberOfItems返回5,为numberOfSections返回5。

然后我的应用程序也因以下错误而崩溃:

'UICollectionView收到索引路径不存在的单元格的布局属性:{length = 2,path = 0 - 5}'

//////===viewcontroller.m==///////
- (void)viewDidLoad {
    self.theData = @[@[@"1",@"2",@"3",@"4",@"5"], @[@"6",@"7",@"8",@"9",@"10"],@[@"11",@"12",@"13",@"14",@"15"],@[@"16",@"17",@"18",@"19",@"20"],@[@"21",@"22",@"23",@"24",@"25"]];
    MultpleLineLayout *layout = [[MultpleLineLayout alloc] init];
    self.collectionView.collectionViewLayout = layout;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.view.backgroundColor = [UIColor blackColor];
    [self.collectionView registerClass:[DataCell class] forCellWithReuseIdentifier:@"DataCell"];
    [self.collectionView reloadData];
}


- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section
{
    return 5;

}

- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView {
    return 5;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView  cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    DataCell *cell = [collectionView  dequeueReusableCellWithReuseIdentifier:@"DataCell" forIndexPath:indexPath];
    cell.label.text = self.theData[indexPath.section ][indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
   // UICollectionViewCell *item = [collectionView cellForItemAtIndexPath:indexPath];
    NSLog(@"%@",indexPath);

}
///////////////////////

任何人都可以解决这个问题吗? 提前谢谢。

3 个答案:

答案 0 :(得分:10)

MultipleLineLayout最初是为无限滚动而编写的,因此该实现存在问题供您使用。它看起来应该是这样的,

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

    NSMutableArray* attributes = [NSMutableArray array];
    for(NSInteger i=0 ; i < self.collectionView.numberOfSections; i++) {
        for (NSInteger j=0 ; j < [self.collectionView numberOfItemsInSection:i]; j++) {
            NSIndexPath* indexPath = [NSIndexPath indexPathForItem:j inSection:i];
            [attributes addObject:[self layoutAttributesForItemAtIndexPath:indexPath]];
        }
    }
    return attributes;
}

答案 1 :(得分:5)

以防其他人在Google上发现这个问题 - 我收到了同样的错误,其中包含一个非常有趣的索引路径:

  

&#39; NSInternalInconsistencyException&#39;,原因:&#39;收到UICollectionView   具有不存在的索引路径的单元格的布局属性:    {length = 2,path = 0 - 0}&#39;

我只是忘记了将集合视图的数据源连接并委托给Interface Builder中的视图控制器。 d&#39;!哦

答案 2 :(得分:0)

对我有用。


    collectionView.reloadData()
    collectionView.collectionViewLayout.invalidateLayout()

这是由于reloadData时单元的自动布局的缓存引起的。