7

I have a UICollectionViewLayout subclass with in it a Supplementary View that contains a multi-line UILabel. The problem is that not all the text is visible at a certain point, how can I give the Supplementary View the height equal to its content?

Example of the layout.

Community
  • 1
  • 1
evenwerk
  • 947
  • 1
  • 12
  • 28

1 Answers1

5

You can find the height of text using below function:-

func labelHeight(width:CGFloat , font:UIFont , text:String)->CGFloat{
    let label:UILabel = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.font = font
    label.text = text
    label.sizeToFit()
    return height:label.frame.height
}

then add this UICollectionViewDelegateFlowLayout method into your controller and return size for your header

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{
   // Pass parameter into this function according to your requirement
  let height = labelHeight(width: collectionView.bounds.width , font:UIFont , text:"")
  return CGSize(width:collectionView.bounds.width , height: height + 10)

}
Irshad Ahmad
  • 1,363
  • 11
  • 17