刚刚开始使用UICollectionView。我使用IB在UIViewController中创建了一个简单的UIViewController。它与分页一起水平滚动。我在UICollectionViewCell中放置了一个简单的UICollectionView。我为单元设置了重用标识符。
我在UILabel中放置了一个标签为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;
}当我运行该应用程序时,视图将正确加载;我可以在两个单元格中水平滚动。我看到了识别每个细胞的丑陋的绿色。
但是,viewWithTag方法返回nil,因此没有设置nameLabel文本。
为什么?
请注意,我还尝试定义UICollectionViewCell的自定义子类并使用它调用registerClass。在IB中,我将单元格类更改为自定义子类,并将UILabel绑定到子类中的UILabel出口。
但这也是行不通的。(无论如何,我倾向于避免使用自定义子类方法,因为似乎没有必要仅仅为了保存IBOutlets而定义类。)
我在想我漏掉了一些显而易见的东西。
下面描述了类似的问题:
Trouble accessing Image from instance of UICollectionViewCell
发布于 2014-01-28 08:16:05
删除registerClass行。你是在故事板上做的,所以你不需要它。
发布于 2014-01-28 07:51:29
试试看
UILabel *nameLabel = (UILabel *)[cell.contentView viewWithTag:100];
更新:
您可以查看单元格的层次结构及其所有子视图的标记:[self showAllSubView:cell] ;,您能找到带有标签10的标签吗?
- (void)showAllSubView:(UIView *)view
{
for (UIView * subView in [view subviews]) {
NSLog(@"%@, tag:%d", subView, subView.tag) ;
[self showAllSubView:subView] ;
}
}https://stackoverflow.com/questions/21399717
复制相似问题