Where to determine the height of the dynamic size of a UICollectionViewCell?

I am using UICollectionViewFlowLayout. My cells contain UILabels that differ in height (number of rows).

It seems that the best way to get cell height would be in a subclass of UICollectionViewCell , because that's where I set the layout and gain access to the internal size of my views, BUT:

collectionView: layout: sizeForItemAtIndexPath: is called before the collectionView: cellForItemAtIndexPath: delegate method, which means I need to know the cell height before I have the actual cell layout.

Everything that I have come up with so far seems too complicated, for example, starting from the height of a fixed cell, referring to the actual height after the marks in the load on the cell and again loading the data with the correct height. Is there a better way to do this?

+5
ios objective-c uicollectionview uicollectionviewcell
source share
1 answer

Unfortunately not.

For elements with dynamic size in a UICollectionView, you need to know or calculate the cell size before creating it. The traditional way to do this is to save the data for each row in the array, and then calculate the size of this data in collectionView:layout:sizeForItemAtIndexPath:

For example, if you have an array of text to display, you can save the NSString objects in an array, measure this line in collectionView:layout:sizeForItemAtIndexPath: and return the size. UICollectionView then takes this size and calls initWithFrame: or setFrame: when adjusting the appearance of the cells.

It would also be nice to cache these sizes if they don't change often.

+3
source share

All Articles