viewWithTag returns nil when initializing a UICollectionViewCell

ios, objective-c, uicollectionview, uicollectionviewcell

Solution

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

Problem

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

Original source