具有给定字体的2行UILabel的高度

时间:2018-01-30 20:48:01

标签: ios swift uilabel

如何使用给定字体计算 2行UILabel 的高度?

我知道,通用多线标签可以通过

动态计算尺寸
let label = UILabel()
label.numberOfLines = 0
label.text = "Some multiline [...] text"

let constraintSize = CGRect(width: aWidth, height: CGFloat.greatestFiniteMagnitude)
let size = aLabel.sizeThatFits(constraintSize)

现在,我想知道的是:如果不知道将在标签中写入的文字,而只知道字体,我怎样才能优雅地计算完全的标签高度 2(或一般 x )行?

优雅含义:也许有人找到比这更好的解决方案:

let label = UILabel()
label.numberOfLines = 2
label.text = "Some really, really, really, [...] long text to make sure it spans at least 2 lines even for the tiniest fonts."

let constraintSize = CGRect(width: aWidth, height: CGFloat.greatestFiniteMagnitude)
let size = aLabel.sizeThatFits(constraintSize)

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

以下内容将为您提供两行文字的大小。用您选择的字体替换字体:

let attrs: [NSAttributedStringKey: Any] = [.font: UIFont.systemFont(ofSize: 17)]
let twoLineHeight = "\n".size(withAttributes: attrs).height

答案 1 :(得分:0)

func labelHeightFor(_ text:String, font:UIFont, width:CGFloat) -> CGFloat{
    let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
    label.numberOfLines = 2
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.font = font
    label.text = text
    label.sizeToFit()
    return label.frame.height
}