Last active
June 10, 2019 00:22
-
-
Save aainaj/c87961015dd2c7982f6d8382a4ada101 to your computer and use it in GitHub Desktop.
Count number of lines of uilabel for max height
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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