UICollectionView Cell Auto Size with AutoLayout iOS 8

Richard Topchii picture Richard Topchii · Dec 30, 2014 · Viewed 11.3k times · Source

I am trying to set up iOS 8 auto sizing cells in UICollectionViewController:
I've created a basic design using StoryBoards and designed one UICollectionViewCell there with a label constrained to the bounds of the cell. Then, I linked that cell's label to a Cell's class to be able to access it programmatically.
Without specifying an estimatedItemSize, everything works fine (except auto sizing, of course).

When I specify estimatedItemSize this way:

- (void)viewDidLoad {
    [super viewDidLoad];
    UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionViewLayout;
    layout.estimatedItemSize = CGSizeMake(100.0f, 30.0f);   
}

Application crashes with these error messages:

the behavior of the UICollectionViewFlowLayout is not defined because:
the item width must be less than the width of the UICollectionView minus the section insets left and right values.
Please check the values return by the delegate.

I think, I am setting estimatedItemSize in a wrong place, or, if I already have a specified item size set up in a storyboard, so it is conflicting somehow with estimated size.

Answer

Richard Topchii picture Richard Topchii · Jan 7, 2015

Answering own question, as I found out the reason for the problem:
To make this feature work, UILabel must have width less than UICollectionView width. Even if in Storyboard it looks OK, if AutoLayout is being used, the width must be constrained, e.g. in my case I made a constraint less or equal 320. Without it, label grows to a very large width but only 1 line height. With this constraint applied, line wrapping started to work and label grew in height instead of width only.