Find number of lines for UILabel – Swift Tutorial

In iOS app development, there are times when it’s necessary to determine the number of lines displayed by a UILabel. This helps in making adjustments to the app’s user interface based on the number of lines the UILabel occupies. In this tutorial, we’ll provide a code snippet that calculates the number of lines in a 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
    }
  }
}