仅使用文本计算 UICollectionViewCell 的高度

Calculating height of UICollectionViewCell with text only

正在尝试计算具有指定宽度的单元格的高度,但无法正确计算。这是一个片段。知道列宽的自定义布局指定了两列。

let cell = TextNoteCell2.loadFromNib()
var frame = cell.frame
frame.size.width = columnWidth // 187.5
frame.size.height = 0 // it does not work either without this line.
cell.frame = frame
cell.update(text: note.text)

cell.contentView.layoutIfNeeded()
let size = cell.contentView.systemLayoutSizeFitting(CGSize(width: columnWidth, height: 0)) // 251.5 x 52.5
print(cell) // 187.5 x 0
return size.height

sizecell.frame 都不正确。

单元格内部有一个文本标签,每个标签边缘有 16 像素的边距。

提前致谢。

您从笔尖加载的单元格没有要放置的视图,因此它的框架不正确。

您需要手动将它添加到视图中,然后对其进行测量,或者您需要将它从 collectionView 中取出,以便它已经在容器视图中

要计算 UILabel 的大小以完全显示给定的文本,我会添加一个助手,如下所示,

extension UILabel {

   public static func estimatedSize(_ text: String, targetSize: CGSize = .zero) -> CGSize {
       let label = UILabel(frame: .zero)
       label.numberOfLines = 0
       label.text = text
       return label.sizeThatFits(targetSize)
   }
}

现在您知道文本需要多少大小,您可以通过添加您在单元格中指定的边距来计算单元格大小,即每边 16.0,因此计算应如下所示,

let intrinsicMargin: CGFloat = 16.0 + 16.0
let targetWidth: CGFloat = 187.0 - intrinsicMargin
let labelSize = UILabel.estimatedSize(note.text, targetSize: CGSize(width: targetWidth, height: 0))
let cellSize = CGSize(width: labelSize.width + intrinsicMargin, height: labelSize.height + intrinsicMargin)

希望您能得到所需的结果。另一项改进是根据屏幕尺寸和列数而不是硬编码 187.0

来计算宽度

对于Swift4.2更新的答案是在uilabel文本的基础上处理uicollectionview Cell的高度和宽度

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
  let size = (self.FILTERTitles[indexPath.row] as NSString).size(withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14.0)])
    return CGSize(width: size.width + 38.0, height: size.height + 25.0)


}