Skip to content

Instantly share code, notes, and snippets.

@gatherheart
Forked from fuxingloh/UILabelCountLines.swift
Created February 25, 2022 04:26
Show Gist options
  • Save gatherheart/aaa016629e8b2defb7ac7597a7edeb80 to your computer and use it in GitHub Desktop.
Save gatherheart/aaa016629e8b2defb7ac7597a7edeb80 to your computer and use it in GitHub Desktop.
iOS Swift: How to check if UILabel is truncated? Calculate number of lines for UILabel
func countLabelLines(label: UILabel) -> Int {
// Call self.layoutIfNeeded() if your view uses auto layout
let myText = label.text! as NSString
let rect = CGSize(width: label.bounds.width, height: CGFloat.greatestFiniteMagnitude)
let labelSize = myText.boundingRect(with: rect, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: label.font], context: nil)
return Int(ceil(CGFloat(labelSize.height) / label.font.lineHeight))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment