Created
September 26, 2012 04:17
-
-
Save ijoshsmith/3785992 to your computer and use it in GitHub Desktop.
Inspect a View's NIB to determine its preferred/natural size
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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