How to check if UILabel is truncated?

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

    To add to iDev 's answer, you should use intrinsicContentSize instead of frame, to make it works for Autolayout

    - (BOOL)isTruncated:(UILabel *)label{
            CGSize sizeOfText = [label.text boundingRectWithSize: CGSizeMake(label.intrinsicContentSize.width, CGFLOAT_MAX)
                                                         options: (NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                                      attributes: [NSDictionary dictionaryWithObject:label.font forKey:NSFontAttributeName] context: nil].size;
    
            if (self.intrinsicContentSize.height < ceilf(sizeOfText.height)) {
            return YES;
        }
        return NO;
    }
    

提交回复
热议问题