Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

viewWithTag returns nil when initializing a 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.

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

like image 767
Daniel Avatar asked Jan 28 '14 07:01

Daniel


2 Answers

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

like image 116
Odrakir Avatar answered Oct 18 '22 00:10

Odrakir


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] ;
    }
}
like image 20
KudoCC Avatar answered Oct 18 '22 01:10

KudoCC