Skip to content

Instantly share code, notes, and snippets.

@ijoshsmith
Created September 26, 2012 04:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ijoshsmith/3785992 to your computer and use it in GitHub Desktop.
Save ijoshsmith/3785992 to your computer and use it in GitHub Desktop.
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