If you for some reason need the number of lines, you can use following extension on UILabel
:
extension UILabel {
func linesNeeded() -> Int {
self.layoutIfNeeded()
let myText = self.text! as NSString
let boundingRectangle = CGSize(width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude)
let labelSize = myText.boundingRect(with: boundingRectangle,
options: .usesLineFragmentOrigin,
attributes: [NSAttributedStringKey.font: self.font],
context: nil)
return (labelSize.height / self.font.lineHeight)
}
}
However, if you don't need the height, you just want to allow the label to show the whole text, you should set label.numberOfLines = 0
which will allow the label to grow as needed.