How to check if UILabel is truncated?

前端 未结 20 2711
不知归路
不知归路 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:36

    To handle iOS 6 (yes, some of us still have to), here's yet another expansion to @iDev's answer. The key takeaway is that, for iOS 6, to make sure your UILabel's numberOfLines is set to 0 before calling sizeThatFits; if not, it'll give you a result that says "the points to draw numberOfLines worth of height" is needed to draw the label text.

    - (BOOL)isTruncated
    {
        CGSize sizeOfText;
    
        // iOS 7 & 8
        if([self.text respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)])
        {
            sizeOfText = [self.text boundingRectWithSize:CGSizeMake(self.bounds.size.width,CGFLOAT_MAX)
                                                 options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                              attributes:@{NSFontAttributeName:self.font}
                                                 context:nil].size;
        }
        // iOS 6
        else
        {
            // For iOS6, set numberOfLines to 0 (i.e. draw label text using as many lines as it takes)
            //  so that siteThatFits works correctly. If we leave it = 1 (for example), it'll come
            //  back telling us that we only need 1 line!
            NSInteger origNumLines = self.numberOfLines;
            self.numberOfLines = 0;
            sizeOfText = [self sizeThatFits:CGSizeMake(self.bounds.size.width,CGFLOAT_MAX)];
            self.numberOfLines = origNumLines;
        }
    
        return ((self.bounds.size.height < sizeOfText.height) ? YES : NO);
    }
    

提交回复
热议问题