Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CollectionViewLayout Supplementary View height equal to content

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.

like image 702
evenwerk Avatar asked Jul 04 '17 09:07

evenwerk


People also ask

How do I make a collection view dynamic height?

Make-CollectionView-Height-Dynamic-According-to-ContentAdd a height constraint to your collection view. Set its priority to 999. Set its constant to any value that only makes it reasonably visible on the storyboard. Change the bottom equal constraint of the collection view to greater or equal.

What are supplementary views?

Supplementary views are more related to your data. The collection view layout still decides where to put them, but they are provided by the collection view data source, just like regular cells.

What is Uicollectionviewflowlayout?

A layout object that organizes items into a grid with optional header and footer views for each section.

What is compositional layout in Swift?

A compositional layout is a type of collection view layout. It's designed to be composable, flexible, and fast, letting you build any kind of visual arrangement for your content by combining — or compositing — each smaller component into a full layout.


1 Answers

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)

}
like image 113
Irshad Ahmad Avatar answered Oct 24 '22 18:10

Irshad Ahmad