Question

What's the role of registerClass:forCellWithReuseIdentifier: method? According to Apple's developer documentation it's supposed to

"Register a class for use in creating new collection view cells."

When I try to use it my project I get a black collection view. When I delete it everything works fine.

#define cellId @"cellId"
#import "ViewController.h"
#import "Cell.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property(strong, nonatomic)NSMutableArray * photoArray;


@end

@implementation ViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSLog(@"%@",_photoArray);
    _photoArray = [[NSMutableArray alloc]initWithCapacity:0];
    [_collectionView registerClass:[Cell class] forCellWithReuseIdentifier:cellId];
    for(int i=1;i<=12;i++)
    {
        NSString * imgName = [NSString stringWithFormat:@"%d.png",i];
        UIImage *img  = [UIImage imageNamed:imgName];
        [_photoArray addObject:img];
    }
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _photoArray.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    Cell* cell = [_collectionView  dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    cell.cellImage.image = [_photoArray objectAtIndex:indexPath.row];
    return cell;
}
Was it helpful?

Solution

If you've already created your UICollectionView in Storyboard, connected your dataSource and delegate, and you have added all of the required methods:

  • numberOfItemsInSection
  • numberOfSectionsInCollectionView (not a required method - refer to this comment)
  • cellForItemAtIndexPath

Then the registerClass / registerCell method isn't required. However, if you need to reuse a view, data, or cells then you should use those methods so that iOS can populate your UICollectionView as needed. This can also be done in your Storyboard by setting the Prototype Cell (the same principle as the registerClass method.

Also, if you're looking for a good explanation on what registerCell does and how to use it check out this link and scroll to the bottom section titled "Cell and View Reuse."

OTHER TIPS

Agree with RazorSharp's answer and wanted to point out that that key phrase for me in the Techtopia link is:

If the cell class was written in code, the registration is performed using the registerClass: method of UICollectionView, otherwise use registerNib

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top