-
-
Save prat14k/9a57716db9c71ba9449fcc15f7e358b8 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)) | |
} | |
extension UILabel { | |
var isTruncated: Bool { | |
guard let labelText = text else { | |
return false | |
} | |
let labelTextSize = (labelText as NSString).boundingRect(with: CGSize(width: frame.size.width, height: .greatestFiniteMagnitude),options: .usesLineFragmentOrigin,attributes: [NSAttributedStringKey.font: font],context: nil).size | |
return labelTextSize.height > bounds.size.height | |
} | |
var numberOfLinesVisible : Int { | |
if let text = text{ | |
// cast text to NSString so we can use sizeWithAttributes | |
let myText = text as NSString | |
//Set attributes | |
let attributes = [NSAttributedStringKey.font : font!] | |
//Calculate the size of your UILabel by using the systemfont and the paragraph we created before. Edit the font and replace it with yours if you use another | |
let labelSize = myText.boundingRect(with: CGSize(width: bounds.width,height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: attributes, context: nil) | |
//Now we return the amount of lines using the ceil method | |
let lines = ceil(CGFloat(labelSize.height) / font.lineHeight) | |
return Int(lines) | |
} | |
return 0 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment