Determine the size of a View by inspecting its NIB

I was exploring the UICollectionView API tonight and stumbled upon an old problem. Both UITableView and UICollectionView ask their delegate for size information about the cells they display. When creating cells in separate XIB files, which I normally do, this means that the delegate must somehow know how big the root View is in that XIB. The easiest way to do that is evil: hard-code the cell’s size in the delegate. Duplication! Yuck!! No more!!!

It dawned on me that this entire problem can be avoided by doing a one-time lookup of the View’s natural size, as it exists in the XIB file (and, at run-time, in the view’s NIB). I posted a Gist on GitHub that shows my simple solution:

// This code assumes that ARC is enabled.
// Returns the size of this View in its NIB.
+ (CGSize)preferredSize
static NSValue *sizeBox = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// Assumption: The XIB file name matches this UIView subclass name.
UINib *nib = [UINib nibWithNibName:NSStringFromClass(self) bundle:nil];
// Assumption: The XIB file only contains a single root UIView.
UIView *rootView = [[nib instantiateWithOwner:nil options:nil] lastObject];
// Cache the size of the UIView in its natural state.
sizeBox = [NSValue valueWithCGSize:rootView.frame.size];
return [sizeBox CGSizeValue];
/* Example usage
– (CGSize)collectionView:(UICollectionView *)collectionView
sizeForItemAtIndexPath:(NSIndexPath *)indexPath
return [JASCollectionViewCell preferredSize];

Happy coding!

This entry was posted in Interface Builder, Tips and Tricks, UICollectionView, UITableView. Bookmark the permalink.