viewWithTag returns nil when initializing a UICollectionViewCell

别说谁变了你拦得住时间么 提交于 2019-12-06 01:31:14

问题


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.

I placed a UILabel with a tag of 100 inside the UICollectionViewCell.

In viewDidLoad, I call:

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

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.

However, the viewWithTag method returns nil and therefore the nameLabel text is not set.

Why?

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.

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:

Trouble accessing Image from instance of UICollectionViewCell


回答1:


Remove the registerClass line. You are doing it on storyboard, so you don't need it.




回答2:


try it

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

Update:

You can look the cell's hierarchy and all its subview's tag :[self showAllSubView:cell] ;, can you find your label with tag 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/viewwithtag-returns-nil-when-initializing-a-uicollectionviewcell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!