Since iOS 8 [UIColletionViewCell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]
returns a size with height of 0.
Here's what the code does:
To determine the size for cell in a UICollectionView
in iOS 7 I use systemLayoutSizeFittingSize:
on a cell defined in a xib file using auto layout. The size depends on the font size of an UILabel
being a subview of the UICollectionViewCell
in my xib file. The label's font is set to UIFontTextStyleBody
. So basically the cell's size depends on the font size setting made in iOS 7.
Here is the code itself:
+ (CGSize)cellSize { UINib *nib = [UINib nibWithNibName:NSStringFromClass([MyCollectionViewCell class]) bundle:nil]; // Assumption: The XIB file only contains a single root UIView. UIView *rootView = [[nib instantiateWithOwner:nil options:nil] lastObject]; if ([rootView isKindOfClass:[MyCollectionViewCell class]]) { MyCollectionViewCell *sampleCell = (MyCollectionViewCell*)rootView; sampleCell.label.text = @"foo"; // sample text without bar [sampleCell setNeedsLayout]; [sampleCell layoutIfNeeded]; return [sampleCell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; } return CGSizeZero; }
It works perfectly fine in iOS 7 but not in iOS 8. Unfortunately I have no clue why.
PS: Using
return [sampleCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
instead of
return [sampleCell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
as somebody might suggest, doesn't make any difference.
What you need to do is wrap all of your content in a container view, then call:
return [sampleCell.containerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
Your cell should look like this: cell -> containerView -> sub views
This works on both ios7 & ios8.
Supposedly on ios8, all you have to do is set the estimateSize & cell will automatically auto size on its own. Apparently that's not working as of beta 6.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With