ViewWithTag returns nil when initializing a UICollectionViewCell

Just start with a UICollectionView . I used IB to create a simple UICollectionView in a UIViewController . It scrolls horizontally under the paging. I placed a simple UICollectionViewCell inside a UICollectionView . I set the reuse id for the cell.

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

In viewDidLoad I call:

 [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"Thing"]; 

Later I will try to initialize the cell as follows:

 - (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 launch the application, the view loads correctly; I can scroll horizontally through 2 cells. I see an ugly green color identifying each cell.

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

Why?

Note that I also tried to define a custom subclass of UICollectionViewCell and call registerClass with it. In IB, I change the cell class to a custom subclass, and I bind UILabel to the output of UILabel in the subclass.

But that doesn't work either. (I would prefer to avoid subclassing the custom subclass anyway, because there is no need to define classes just to hold IBOutlets .)

I think I missed something obvious here.

A similar problem described here:

Failed to access image from UICollectionViewCell instance.

+6
source share
2 answers

Delete the registerClass line. You do this on a storyboard, so you don't need it.

+26
source

try

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

Update:

You can see the hierarchy of cells and your entire subview tag: [self showAllSubView:cell] ; , can you find the tag with tag 10?

 - (void)showAllSubView:(UIView *)view { for (UIView * subView in [view subviews]) { NSLog(@"%@, tag:%d", subView, subView.tag) ; [self showAllSubView:subView] ; } } 
+1
source

All Articles