Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView Cell Auto Size with AutoLayout iOS 8

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.

like image 356
Richard Topchii Avatar asked Dec 30 '14 15:12

Richard Topchii


People also ask

What is Collectionviewlayout?

An abstract base class for generating layout information for a collection view.

What is Uicollectionviewflowlayout?

A layout object that organizes items into a grid with optional header and footer views for each section.

What is the use of datasource and delegate in UICollectionView in IOS?

This method asks the data source object to provide a supplementary view to display in the collection view. It asks the datasource object whether the specified item can be moved to another location in the collectionview. This method moves the specified item to the specified indexpath.


1 Answers

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.

like image 126
Richard Topchii Avatar answered Sep 28 '22 20:09

Richard Topchii