I’ve just starting playing around with UICollectionView for the first time. Seems to work nicely, but having an issue and a question about it.
I have my UICollectionView setup as below and with a custom cell:
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section
{
return 10;
}
- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView
{
return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
ContactCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
cell.nameLbl.text = @"text";
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(145, 95);
}
- (UIEdgeInsets)collectionView:
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(10, 10, 10, 10);
}
So this is all dandy, however I have added this line to viewDidLoad:
[collectionView registerClass:[ContactCell class] forCellWithReuseIdentifier:@"Cell"];
This is causing trouble and I don’t understand why. When I enable this line, all of my cells go blank. How come? What am I missing?
Also, as I understand it, if that line enables reusable cells, why do I have to with a collection view vs not having to in a table view?
You storyboard is automatically registering the cell you designed in the storyboard for the reuse identifier you specified for that cell in the right hand pane in interface builder. By re-registering your class for that reuse identifier the collection view simply calls alloc init on your subclass and expects the view to be setup programmatically.
From the documentation:
If you want to design cells outside of the storyboard you can either setup your interface programmatically or set up a cell in a seperate xib and then call
- (void)registerNib:(UINib *)nib forCellWithReuseIdentifier:(NSString *)identifierWhere the nib must have one top level view which is a cell of your custom subclass with the right reuse identifier set in interface builder.