Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a get the auto layout size of the UICollectionViewCells in iOS 8? (systemLayoutSizeFittingSize returns size with zero height in iOS 8)

Tags:

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.

How can I get the auto layout size of the UICollectionViewCells in iOS 8?

PS: Using

 return [sampleCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; 

instead of

 return [sampleCell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; 

as somebody might suggest, doesn't make any difference.

like image 531
martn_st Avatar asked Aug 12 '14 13:08

martn_st


1 Answers

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.

like image 60
Triet Luong Avatar answered Oct 13 '22 00:10

Triet Luong