Created
June 10, 2019 00:24
-
-
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
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) | |
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