Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aainaj/9f46b143fa834ff8cad46e6beb338850 to your computer and use it in GitHub Desktop.
Save aainaj/9f46b143fa834ff8cad46e6beb338850 to your computer and use it in GitHub Desktop.
Count number of lines of uilabel for max height for all screen sizes
func countLines(of label: UILabel, maxHeight: CGFloat) -> Int {
// viewDidLayoutSubviews() in ViewController or layoutIfNeeded() in view subclass
guard let labelText = label.text else {
return 0
}
let rect = CGSize(width: label.bounds.width, height: maxHeight)
let labelSize = labelText.boundingRect(with: rect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: label.font!], context: nil)
let lines = Int(ceil(CGFloat(labelSize.height) / label.font.lineHeight))
return labelText.contains("\n") && lines == 1 ? lines + 1 : lines
}
// maxHeight is just an example. It needs to be calculated dynamically for all screen sizes.
label.numberOfLines = countLines(of: label, maxHeight: 180)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment