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.
source share