问题描述
只需开始使用 UICollectionView
.我已经使用IB在 UIViewController
中创建了一个简单的 UICollectionView
.它与分页一起水平滚动.我在 UICollectionView
内放置了一个简单的 UICollectionViewCell
.我设置了单元的重用标识符.
Just getting started with UICollectionView
. I've used IB to create a simple UICollectionView
in a UIViewController
. It scrolls horizontally with paging. I placed a simple UICollectionViewCell
inside the UICollectionView
. I set the reuse identifier for the cell.
我在 UICollectionViewCell
内放置了一个标签为100的 UILabel
.
I placed a UILabel
with a tag of 100 inside the UICollectionViewCell
.
在 viewDidLoad
中,我叫:
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"Thing"];
稍后,我尝试像这样初始化单元格:
Later I attempt to initialize the cell like so:
- (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个单元格中水平滚动.我看到难看的绿色标识了每个单元格.
When I run the app, the view loads correctly; I can scroll horizontally through the 2 cells. I see the ugly green color identifying each cell.
但是, viewWithTag
方法返回 nil
,因此未设置nameLabel文本.
However, the viewWithTag
method returns nil
and therefore the nameLabel text is not set.
为什么?
请注意,我还尝试了定义 UICollectionViewCell
的自定义子类,并使用它来调用registerClass.在IB中,我将单元格类更改为自定义子类,并将 UILabel
绑定到子类中的 UILabel
出口.
Note that I also tried defining a custom subclass of UICollectionViewCell
and calling registerClass with it. In IB, I change the cell class to the custom subclass and I bind the UILabel
to the UILabel
outlet in the subclass.
但这也不起作用.(我还是想避免使用自定义子类方法,因为似乎不必仅仅为了容纳 IBOutlets
而定义类.)
But this also does not work. (I would prefer to avoid the custom subclass approach anyway because it does not seem necessary to define classes just to hold IBOutlets
.)
我在想我这里缺少明显的东西.
I'm thinking that I'm missing something obvious here.
这里描述了类似的问题:
Similar problem described here:
推荐答案
删除registerClass行.您正在情节提要中执行此操作,因此不需要它.
Remove the registerClass line. You are doing it on storyboard, so you don't need it.
这篇关于初始化UICollectionViewCell时viewWithTag返回nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!