I'm using UICollectionViewFlowLayout. My cells contain UILabels that differ in height (number of lines).
It seems that the best way to get the cell height would be in the subclass of UICollectionViewCell
, because that is where I set the layout and have access to intrinsic size of my views, BUT:
collectionView: layout: sizeForItemAtIndexPath:
is called before the collectionView: cellForItemAtIndexPath:
delegate method, which means that I need to know the cell height before I have the actual layout of the cell.
Everything I came up with so far seems too complicated, like starting with fixed cell height, referencing actual height after labels in the cell load and reloading the data again with correct height. Is there a better way to do this?
Unfortunately, no.
For dynamically sized items in UICollectionView you need to know or compute the size of the cell before it is created. The traditional way to do this is to store the data for each row in an array and then compute the size of that data in collectionView:layout:sizeForItemAtIndexPath:
.
For example, if you had an array of text to be displayed you could store the NSString
objects in an array, measure that string in collectionView:layout:sizeForItemAtIndexPath:
and return the size. UICollectionView
then takes that size and calls initWithFrame:
or setFrame:
when configuring your cell's view.
It's also not a bad idea to cache these sizes if they don't change often.
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