How can I calculate the height of a 2-line UILabel with a given font?
I know, that there's a way for general multiline labels to dynamically calculate their size by
let label = UILabel()
label.numberOfLines = 0
label.text = "Some multiline [...] text"
let constraintSize = CGRect(width: aWidth, height: CGFloat.greatestFiniteMagnitude)
let size = aLabel.sizeThatFits(constraintSize)
Now, what I want to know: Without knowing the text that'll be written in the label, but only the font, how can I elegantly calculate the height of the label spanning exactly 2 (or generally x) lines?
Elegantly meaning: Maybe somebody finds a better solution than this:
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)
Appreciate your help!
The following will give you the size for two lines of text. Replace the font with your chosen font:
let attrs: [NSAttributedStringKey: Any] = [.font: UIFont.systemFont(ofSize: 17)]
let twoLineHeight = "\n".size(withAttributes: attrs).height