Find number of lines for UILabel – Swift Tutorial

In iOS app development, sometimes we do need to find number of lines shown by our UILabel. So that we can make adjustment to our app user interface via finding number of lines UILabel has drawn. In this tutorial we will get a code snippet that exactly does same thing, i.e. calculating number of line of UILabel.

Code snippet to calculating number of lines for UILabel

extension UILabel {
  func countLines() -> Int {
    guard let myText = self.text as NSString? else {
      return 0
    }
    // Call self.layoutIfNeeded() if your view uses auto layout
    let rect = CGSize(width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude)
    let labelSize = myText.boundingRect(with: rect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: self.font as Any], context: nil)
    return Int(ceil(CGFloat(labelSize.height) / self.font.lineHeight))
  }
}

How to use UILabel extension to find number of lines for UILabel

class ViewController: UIViewController {
  @IBOutlet weak var labelTitle: UILabel!

  override func viewDidLoad() {
    if labelTitle.countLines() >= 2 {
      // Do some stuff
    }
  }
}