UICollectionView cellForItemAtIndexPath 为空。

28
我有一个更新现有UICollectionView的函数。 UICollectionView已被创建,我可以看到它,但是当我想要访问其单元格以进行更新时,它们为空。

我有一个更新现有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;
}

日志:

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

你是获取所有单元格为空还是获取一些单元格后再获取空值? - CRDave
虽然这里的答案可行,但如果可以的话,最好直接在数据模型上调用 [cell finishExam],而不是通过 collectionView 代理。请参阅我对 Paul S. 答案的评论。在大多数情况下,您应该能够从 collectionViewLayout 属性中获取单元格布局信息,并且像 -finishExam 这样的模型特定功能应该在您的模型上可用,或者在单元格出列时进行配置。 - nteissler
2个回答

54

来自UICollectionView文档(强调是我的)

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

您应该更新提供视图数据的底层模型。


10
这对我有用,但除了使用[view reloadData]重新加载数据外,我还必须按照https://dev59.com/HGEi5IYBdhLWcg3wPKWx#21480786中的建议使用[view layoutIfNeeded]。 - zyzof
28
在调用[collectionView reloadData]后,使用[collectionView layoutIfNeeded]可以使我成功获取单元格。感谢@zyzof。 - Richard McCluskey
3
感谢所有对layoutIfNeeded的支持! :D 只是好奇,有人知道为什么这样做吗?因为在我的情况下,该单元格一直是可见的。 - Happiehappie
1
嘿@RichardMcCluskey,你知道为什么我们要调用这个吗?我注意到所有的UICollectionView都被正确地渲染了,但是如果没有这行调用,cellForItemAtIndexPath每次都会返回nil - Yuchen
1
嗨 @zyzof,你应该将你的建议作为一个单独的回答发布!!那对我非常有帮助! - Yuchen
显示剩余4条评论

19

试试这个:

[collectionView reloadData];
[collectionView layoutIfNeeded];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接