How to check if UILabel is truncated?

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

    Use this category to find if a label is truncated on iOS 7 and above.

    // UILabel+Truncation.h
    @interface UILabel (Truncation)
    
    @property (nonatomic, readonly) BOOL isTruncated;
    
    @end
    
    
    // UILabel+Truncation.m
    @implementation UILabel (Truncation)
    
    - (BOOL)isTruncated
    {
        CGSize sizeOfText =
          [self.text boundingRectWithSize:CGSizeMake(self.bounds.size.width, CGFLOAT_MAX)
                                   options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
                                attributes:@{ NSFontAttributeName : label.font } 
                                   context: nil].size;
    
        if (self.frame.size.height < ceilf(sizeOfText.height))
        {
            return YES;
        }
        return NO;
    }
    
    @end
    

提交回复
热议问题