【发布时间】:2014-01-28 07:49:10
【问题描述】:
刚刚开始使用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;
}
当我运行应用程序时,视图会正确加载;我可以水平滚动 2 个单元格。我看到识别每个单元格的难看的绿色。
但是,viewWithTag 方法返回 nil,因此未设置 nameLabel 文本。
为什么?
请注意,我还尝试定义 UICollectionViewCell 的自定义子类并使用它调用 registerClass。在 IB 中,我将单元类更改为自定义子类,并将UILabel 绑定到子类中的UILabel 插座。
但这也行不通。 (无论如何,我宁愿避免使用自定义子类方法,因为似乎没有必要仅仅为了保存 IBOutlets 而定义类。)
我在想我在这里遗漏了一些明显的东西。
此处描述的类似问题:
Trouble accessing Image from instance of UICollectionViewCell
【问题讨论】:
-
你在哪里创建 UILabel?
-
UILabel 在 Interface Builder 中配置。我不希望在代码中分配它。我在想 viewWithTag 应该检索创建的实例。这就是它与 UITableView 的工作方式。
-
您是否为 nib 中的原型 CollectionViewCell 分配了重用标识符?
-
@chandu 是的,dequeueReusableCellWithReuseIdentifier 返回一个有效的单元格。如果我在这里不匹配,那么应用程序将崩溃。
-
我认为您的 collectionView 单元格不是由您的笔尖中的原型制成的,而是从 RegisterClass 方法创建一个单元格。你必须使用 registerNib 方法。
标签: ios objective-c uicollectionview uicollectionviewcell