My UICollectionView cells contain UILabels with multiline text. I don't know the height of the cells until the text has been set on the label.
-(CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout*)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath;
This was the initial method I looked at to size the cells. However, this is called BEFORE the cells are created out of the storyboard.
Is there a way to layout the collection and size the cells AFTER they have been rendered, and I know the actual size of the cell?
subclass UICollectionViewCell and override
layoutSubviews
like thishereby you will anchor cell leading and trailing edge to collectionView
In iOS 10,
prefetchingEnabled
isYES
by default. WhenYES
, the collection view requests cells in advance of when they will be displayed. It leads to crash in iOS 10I think your are looking for the
invalidateLayout
method you can call on the.collectionViewLayout
property of your UICollectionView. This method regenerates your layout, which in your case means also calling-collectionView: layout: sizeForItemAtIndexPath:
, which is the right place to reflect your desired item size. Jirune points the right direction on how to calculate them.An example for the usage of
invalidateLayout
can be found here. Also consult the UICollectionViewLayout documentation on that method:Edit:
For storyboard collection view which contains auto layout constraints, you need to override
viewDidLayoutSubviews
method ofUIViewController
and callinvalidateLayout
collection view layout in this method.Hey in the above
delegate
method itself, you can calculate theUILabel
size using the below tricky way and return theUICollectionViewCell
size
based on that calculation.