viewWithTag在初始化UICollectionViewCell时返回nil

刚开始使用UICollectionView 。 我用IB在UIViewController创build了一个简单的UICollectionView 。 它与分页水平滚动。 我在UICollectionView放置了一个简单的UICollectionView 。 我为单元格设置了重用标识符。

我在UICollectionViewCell放置了一个标签为100的UICollectionViewCell

viewDidLoad ,我打电话给:

 [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"Thing"]; 

后来我尝试初始化单元格,如下所示:

 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Thing" forIndexPath:indexPath]; cell.backgroundColor = [UIColor greenColor]; UILabel *nameLabel = (UILabel *)[cell viewWithTag:100]; nameLabel.text = @"Bogus"; return cell; } 

当我运行应用程序,视图加载正确; 我可以水平滚动2个单元格。 我看到了识别每个细胞的难看的绿色。

但是, viewWithTag方法返回nil ,因此nameLabel文本未设置。

为什么?

请注意,我也尝试定义UICollectionViewCell的自定义子类,并调用registerClass。 在IB中,我将单元类更改为自定义子类,并将UILabel绑定到子类的UILabelsockets。

但是这也是行不通的。 (我宁愿避免使用自定义子类方法,因为似乎没有必要定义类来保存IBOutlets 。)

我在想我在这里错过了一些明显的东西。

这里描述的类似问题:

无法从UICollectionViewCell实例访问Image

删除registerClass行。 你是在故事板上做的,所以你不需要它。

尝试一下

UILabel *nameLabel = (UILabel *)[cell.contentView viewWithTag:100];

更新:

您可以查看单元格的层次结构及其所有子视图的标签: [self showAllSubView:cell] ; ,你能find标签10的标签吗?

 - (void)showAllSubView:(UIView *)view { for (UIView * subView in [view subviews]) { NSLog(@"%@, tag:%d", subView, subView.tag) ; [self showAllSubView:subView] ; } }