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?
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.
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.
A layout object that organizes items into a grid with optional header and footer views for each section.
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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With