UICollectionView cellForItemAtIndexPath为nil

Lud*_*uda 27 objective-c ios uicollectionview uicollectionviewcell

我有一个更新现有UICollectionView的函数.创建了UICollectionView,我可以看到它,但是当我想访问它的单元格来更新它时,它们是零.

-(void)finishExam{

    for (int i = 0; i < [self.questionsOverviewCollection numberOfItemsInSection:0]; i++) {

        NSLog(@"self.questionsOverviewCollection - %@",self.questionsOverviewCollection);
        NSLog(@"cell - %@",[self.questionsOverviewCollection cellForItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]]);
        NSLog(@"overviewCell - %@",(OverviewCell*)[self.questionsOverviewCollection cellForItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]]);
        NSLog(@"numOfCells - %d", [self.questionsOverviewCollection numberOfItemsInSection:0]);

        OverviewCell *cell = (OverviewCell*)[self.questionsOverviewCollection cellForItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
            [cell finishExam];
    }
}


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

    OverviewCell *cell = (OverviewCell*)[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    [cell someSetUp];

    return cell;
}
Run Code Online (Sandbox Code Playgroud)

日志:

self.questionsOverviewCollection - <UICollectionView: 0xa1abc00; frame = (14 219; 217 441); clipsToBounds = YES; opaque = NO; autoresize = W+H; gestureRecognizers = <NSArray: 0xe0617a0>; layer = <CALayer: 0xe0bbb00>; contentOffset: {0, 0}> collection view layout: <UICollectionViewFlowLayout: 0xe0cc3f0>
cell - (null)
overviewCell - (null)
numOfCells - 30
Run Code Online (Sandbox Code Playgroud)

Pau*_*l.s 51

来自UICollectionView文档(强调我自己)

返回值
相应索引路径中的单元格对象,如果单元格不可见或indexPath超出范围,则为nil.

您应该更新底层模型,该模型为视图提供数据.

  • 调用[collectionView layoutIfNeeded]后,我调用[collectionView reloadData]后获取单元格.谢谢@zyzof (24认同)
  • 这对我有用,但除了使用[view reloadData]重新加载数据外,我还必须按照http://stackoverflow.com/a/21480786/1388195 [查看layoutIfNeeded] (9认同)
  • 非常感谢layoutIfNeeded !!! :D只是想知道,有没有人知道为什么?在我的情况下,单元格在整个时间都可见. (3认同)

zyz*_*zof 13

试试这个:

[collectionView reloadData];
[collectionView layoutIfNeeded];
Run Code Online (Sandbox Code Playgroud)