Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Inspect a View's NIB to determine its preferred/natural size
// 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
layout:(UICollectionViewLayout*)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return [JASCollectionViewCell preferredSize];
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment