gpt4 book ai didi

ios - viewWithTag 在初始化 UICollectionViewCell 时返回 nil

转载 作者:可可西里 更新时间:2023-11-01 03:35:53 25 4
gpt4 key购买 nike

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

我在 UICollectionViewCell 中放置了一个标记为 100 的 UILabel

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;
}

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

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

为什么?

请注意,我还尝试定义 UICollectionViewCell 的自定义子类并使用它调用 registerClass。在 IB 中,我将单元类更改为自定义子类,并将 UILabel 绑定(bind)到子类中的 UILabel socket 。

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

我想我在这里遗漏了一些明显的东西。

此处描述的类似问题:

Trouble accessing Image from instance of UICollectionViewCell

最佳答案

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

关于ios - viewWithTag 在初始化 UICollectionViewCell 时返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21399717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com