Last active
June 4, 2024 08:09
-
-
Save fuxingloh/ccf26bb68f4b8e6cfd02 to your computer and use it in GitHub Desktop.
iOS Swift: How to check if UILabel is truncated? Calculate number of lines for UILabel
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 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)) | |
} |
This returned me 11 even for couple of words.
This returned me 11 even for couple of words.
Please check the width of UILable. Let fix it. I have also been like you.
Thank you very much! You helped a lot) It works)
Code updated to Swift 5 and made as UILabel extension. Also 0
will be returned if the label doesn't have any text.
extension UILabel {
func countLines() -> Int {
guard let myText = self.text as NSString? else {
return 0
}
// Call self.layoutIfNeeded() if your view uses auto layout
let rect = CGSize(width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude)
let labelSize = myText.boundingRect(with: rect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: self.font as Any], context: nil)
return Int(ceil(CGFloat(labelSize.height) / self.font.lineHeight))
}
}
Now you can perform something like:
class MyAwesomeViewController: UIViewController {
@IBOutlet weak var myAwesomeLabel: UILabel!
override func viewDidLoad() {
if myAwesomeLabel.countLines() >= 2 {
// Do some stuff
}
}
}
I have 2 lines UILabels but still this extension shows me 1 line
I have 3 lines UILabels but still this extension shows me 1 line
In order to work you must call it after func viewDidLayoutSubviews()
was called.
It uses the label frame. In viewDidLoad this value is still not correct which leads to you getting incorrect values.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Amazing!!.. I am done.