uilabel tail truncation

后端 未结 4 1432
慢半拍i
慢半拍i 2020-11-30 14:06

Im working on an ios app using objective c and i have an issue with uilabel that i could use some help with. Basically i have a label that can change size to fit the text th

4条回答
  •  天命终不由人
    2020-11-30 14:39

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

    @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
    

提交回复
热议问题