WKInterfacelabel check if truncated

300 Views Asked by At

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 !

2

There are 2 best solutions below

0
On BEST ANSWER

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);
0
On

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
}