2

我有一个UICollectionViewLayout子类,其中包含一个多行UILabel的补充视图。问题是,并非所有的文本在某个特定点都是可见的,我怎样才能使补充视图的高度等于其内容?CollectionViewLayout补充视图高度等于内容

Example of the layout.

+1

也许这将帮助您:https://stackoverflow.com/a/41607018/5381663 – kamil3

回答

1

您可以使用以下功能查找文本的高度: -

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 
} 

再加入这个UICollectionViewDelegateFlowLayout方法到您的控制器和你的头回尺寸

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) 

}