Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to determine the height of a dynamically sized UICollectionViewCell?

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?

like image 867
Alexander Borisenko Avatar asked Oct 02 '22 23:10

Alexander Borisenko


1 Answers

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.

like image 112
nrj Avatar answered Oct 24 '22 02:10

nrj