Label number of lines to 3 from storyboard
Following is my code to find out label text is truncated or not
let size = reviewLbl.text?.size(withAttributes: [.font: reviewLbl.font]) ?? .zero
if (size.height > reviewLbl.frame.size.height) {
}
Also tried following link but it isn't working for me so don't call this as duplicate question
func countLabelLines() -> Int {
// Call self.layoutIfNeeded() if your view is uses auto layout
let myText = self.text! as NSString
let attributes = [NSAttributedString.Key.font : self.font]
let labelSize = myText.boundingRect(with: CGSize(width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes as [NSAttributedString.Key : Any], context: nil)
return Int(ceil(CGFloat(labelSize.height) / self.font.lineHeight))
}
func isTruncatedOrNot() -> Bool {
if (self.countLabelLines() > self.numberOfLines) {
return true
}
return false
}
try this, and self.bound.width is your label width so if you added Label in stack view make sure label width or stackview have proper constraints.
In your case its returning true every time because it might have constraints issue.
Try this extension:
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: [.font: font],
context: nil).size
return labelTextSize.height > bounds.size.height
}
}
and use it like:
if myLabel.isTruncated {
// Show more
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.