Skip to content

Instantly share code, notes, and snippets.

@aainaj
Last active June 10, 2019 00:22
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/c87961015dd2c7982f6d8382a4ada101 to your computer and use it in GitHub Desktop.
Save aainaj/c87961015dd2c7982f6d8382a4ada101 to your computer and use it in GitHub Desktop.
Count number of lines of uilabel for max height
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)
return Int(ceil(CGFloat(labelSize.height) / label.font.lineHeight))
}
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