artooras
artooras

Reputation: 6795

UICollectionViewCell with Interface Builder

I have the following nib setup in Interface Builder that contains my viewController's main view (with UICollectionView) and reusable views for header and cells

enter image description here

I register for reusable views in viewDidLoad

[self.calendarView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"dayCell"];
[self.calendarView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"dayCellDisabled"];
[self.calendarView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"monthHeader"];

When I try to access my cell label like this:

UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"dayCellDisabled" forIndexPath:indexPath];    
UILabel *dayLabel = (UILabel *)[cell viewWithTag:1];

the resulting dayLabel is nil, therefore I cannot assign it a value, and my view displays nothing. The same applies to my reusable header view and its Year and Month labels.

What am I doing wrong here?

Upvotes: 2

Views: 1080

Answers (1)

jrturton
jrturton

Reputation: 119242

What am I doing wrong here?

Several things:

  • Registering a nib for cell reuse requires that the cell be the top-level object in that nib - you can't have a multi-content nib like this. Either pull the cell out into a separate nib or use a storyboard and prototypes
  • Registering a class for cell reuse implies that you will be building the cell's contents in code, which I guess you're not doing given the above. A registered class has no knowledge of that nib file.
  • Tags are almost always the wrong thing to do - create a subclass and use outlets instead.

Upvotes: 5

Related Questions