What's a recommended approach to determine the height of UICollectionViewCell
which contains several text views whose height depends on the text content set in them?
Since UICollectionView's sizeForItemAt
is called before cellForItemAt
the definitive text content isn't known at the time the cell size should be calculated.
One possible way would be to calculate the text height with something like
func calculateEstimatedCellFrame(_ text:String) -> CGRect
{
let size = CGSize(width: 210, height: 1000)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
return NSString(string: text).boundingRect(with: size, options: options, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14)], context: nil)
}
But that seems impractical in my current case, especially since the texts for the cells is at least in part assembled from various other sources (in part from JSON data, and from localization strings).
Using constraints seems very complex and I'm not sure how I would apply them to have several text views that are placed between other text views to set their proper constraint values.
Is there any better way to figure out the required height for each cell?