0

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?

Muneeb Ali
  • 452
  • 6
  • 12
BadmintonCat
  • 9,002
  • 10
  • 64
  • 114
  • possible duplicate of https://stackoverflow.com/questions/28161839/uicollectionview-dynamic-cell-height – Alexandr Kolesnik Aug 01 '19 at 09:03
  • take a look at. https://stackoverflow.com/questions/25895311/uicollectionview-self-sizing-cells-with-auto-layout – Vikky Aug 01 '19 at 10:07
  • Thanks AlexandrKolesnik, Vikky but none of the links posted are conclusive in my case. Just vague directions into what might work. So far they weren't any help. None of the solutions explained in them worked with dynamic textview height. – BadmintonCat Aug 02 '19 at 02:50

0 Answers0