Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the height of a UILabel in Swift?

Tags:

uilabel

swift

I am a beginner in Swift and I am trying to get the height of a label. The label has multiple lines of text. I want to know the total height it occupies on the screen.

like image 533
vb11 Avatar asked Apr 08 '16 20:04

vb11


1 Answers

Swift 4 with extension

extension UILabel{

public var requiredHeight: CGFloat {
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: frame.width, height: CGFloat.greatestFiniteMagnitude))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.font = font
    label.text = text
    label.attributedText = attributedText
    label.sizeToFit()
    return label.frame.height
  }
}
like image 66
levin varghese Avatar answered Nov 15 '22 16:11

levin varghese