I would like to check if the text in WKInterfacelabel is truncated. Since there is no text property and it seems I can not get the number of lines property that you can set in storyboard I wonder if there is any way or trick on how to achieve this!?
Thanks !
You can get the number of lines that a label takes to display given text using below code.
CGFloat labelWidth = 100.0f;
NSString *text = @"some text";
[self.label setText:text];
[self.label setWidth:labelWidth];
UIFont *font = [UIFont systemFontOfSize:12.0f];
CGRect rect = [text boundingRectWithSize:CGSizeMake(labelWidth, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName : font}
context:nil];
CGFloat numOfLines = ceil(rect.size.height / font.lineHeight);
Swift version of @Sahana 's answer above
func isTruncated(text: String, width: CGFloat, font: UIFont, numOfLines: Int) -> Bool {
let rect = text.boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)),
options: .usesLineFragmentOrigin,
attributes: [NSAttributedString.Key.font : font],
context: nil)
let thisNumOfLines = Int(ceil(rect.size.height / font.lineHeight))
let isTruncated = thisNumOfLines > numOfLines
return isTruncated
}
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.