Smart Collection View Cells

I was recently introduced to a neat way for UITableViewCells to automatically wire their own XIBs and register themselves with their parent table view. This nicely moves the responsibility for doing this out of table view and into the table view cell itself…makes for a generally cleaner table view controller “.m” class in general, especially when dealing with tables that can have multiple different cell types.

The same is true of UICollectionViewController. Here is a handy class to help do the same:

To use them, just put something like this in –
– (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;

RestaurantCollectionViewCell *cell = [RestaurantCollectionViewCell cellForCollectionView:self.collectionView forIndexPath:indexPath];

@interface SmartCollectionViewCell : UICollectionViewCell

+(NSString*)cellIdentifier;
+(id)cellForCollectionView:(UICollectionView*)collectionView fromNib:(UINib*)nib forIndexPath:(NSIndexPath*)indexPath;
+(id)cellForCollectionView:(UICollectionView*)collectionView forIndexPath:(NSIndexPath*)indexPath;
+(UINib*)nib;

@end

#import "SmartCollectionViewCell.h"

@implementation SmartCollectionViewCell

+(id)cellForCollectionView:(UICollectionView*)collectionView
                   fromNib:(UINib*)nib
              forIndexPath:(NSIndexPath*)indexPath{

    NSString *cellIdentifier = [self cellIdentifier];
    [collectionView registerClass:[self class]
            forCellWithReuseIdentifier:cellIdentifier];
    [collectionView registerNib:nib forCellWithReuseIdentifier:cellIdentifier];
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier
                                                                           forIndexPath:indexPath];
    return cell;
}

+(id)cellForCollectionView:(UICollectionView*)collectionView
              forIndexPath:(NSIndexPath*)indexPath{
    return [[self class] cellForCollectionView:collectionView
                                       fromNib:[self nib]
                                  forIndexPath:indexPath];
}

+ (NSString *)nibName {
    return [self cellIdentifier];
}

+ (NSString *)cellIdentifier {
    [NSException raise:NSInternalInconsistencyException format:@"WARNING: YOU MUST OVERRIDE THIS GETTER IN YOUR CUSTOM CELL .M FILE"];
    static NSString* _cellIdentifier = nil;
    _cellIdentifier = NSStringFromClass([self class]);
    return _cellIdentifier;
}

+(UINib*)nib{
    NSBundle * classBundle = [NSBundle bundleForClass:[self class]];
    UINib * nib = [UINib nibWithNibName:[self nibName]
                                 bundle:classBundle];
    return nib;
}

@end