How to check if UILabel is truncated?

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

    I have written a category for working with UILabel's truncation. Works on iOS 7 and later. Hope it helps ! uilabel tail truncation

    @implementation UILabel (Truncation)
    
    - (NSRange)truncatedRange
    {
        NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:[self attributedText]];
    
        NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
        [textStorage addLayoutManager:layoutManager];
    
        NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:[self bounds].size];
        textContainer.lineFragmentPadding = 0;
        [layoutManager addTextContainer:textContainer];
    
        NSRange truncatedrange = [layoutManager truncatedGlyphRangeInLineFragmentForGlyphAtIndex:0];
        return truncatedrange;
    }
    
    - (BOOL)isTruncated
    {
        return [self truncatedRange].location != NSNotFound;
    }
    
    - (NSString *)truncatedText
    {
        NSRange truncatedrange = [self truncatedRange];
        if (truncatedrange.location != NSNotFound)
        {
            return [self.text substringWithRange:truncatedrange];
        }
    
        return nil;
    }
    
    @end
    

提交回复
热议问题