How to check if UILabel is truncated?

前端 未结 20 2779
不知归路
不知归路 2020-11-28 02:53

I have a UILabel that can be varying lengths depending on whether or not my app is running in portrait or landscape mode on an iPhone or iPad. When the text is

20条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 03:13

    EDIT: I just saw my answer was upvoted, but the code snippet I gave is deprecated.
    Now the best way to do this is (ARC) :

    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    paragraph.lineBreakMode = mylabel.lineBreakMode;
    NSDictionary *attributes = @{NSFontAttributeName : mylabel.font,
                                 NSParagraphStyleAttributeName : paragraph};
    CGSize constrainedSize = CGSizeMake(mylabel.bounds.size.width, NSIntegerMax);
    CGRect rect = [mylabel.text boundingRectWithSize:constrainedSize
                                             options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                          attributes:attributes context:nil];
    if (rect.size.height > mylabel.bounds.size.height) {
        NSLog(@"TOO MUCH");
    }
    

    Note the calculated size is not integer value. So if you do things like int height = rect.size.height, you will lose some floating point precision and may have wrong results.

    Old answer (deprecated) :

    If your label is multiline, you can use this code :

    CGSize perfectSize = [mylabel.text sizeWithFont:mylabel.font constrainedToSize:CGSizeMake(mylabel.bounds.size.width, NSIntegerMax) lineBreakMode:mylabel.lineBreakMode];
    if (perfectSize.height > mylabel.bounds.size.height) {
        NSLog(@"TOO MUCH");
    }
    

提交回复
热议问题