ios - CollectionViewLayout 补充 View 高度等于内容

标签 ios swift uicollectionview uicollectionviewlayout uicollectionreusableview

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

Example of the layout.

最佳答案

您可以使用以下函数找到文本的高度:-

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 方法添加到您的 Controller 中并返回标题的大小

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)

}

关于ios - CollectionViewLayout 补充 View 高度等于内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44901670/

相关文章:

ios - 通知消息/警报消息和 UICollectionView :

ios - Firebase Debug模式不上传日志事件

ios - Facebook 使用 iOS 集成,坏了两天

ios - 如何从 'SKScene' 调用我的 'ViewController' 中的方法

ios - 边输入边搜索 Swift

swift - 从多个 UICollectionVIews 内部的 UICollectionViewCell 推送一个新的 UICollectionViewController

ios - 从存储中下载图像时出现可选错误,我已将字符串转换为 URL

iOS-Charts StackedBar值显示

ios - UIImage 方向 Swift

ios - Collection View ( Collection View ,didSelectItemAt : indexPath) - Cannot call value of non-function type 'UICollectionView