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.

1

1 Answer 1

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)

}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.