uilabel tail truncation

后端 未结 4 1419
慢半拍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
    
    0 讨论(0)
  • 2020-11-30 14:55

    lineBreakMode is a switch. It can be either (for iOS6+) NSLineBreakByWordWrapping or NSLineBreakByTruncatingTail but not both.

    But, to answer your question, you can find the size of some text using the class extensions in NSString+UIKit. Having found the size you could update the frame of the UILabel appropriately.

    0 讨论(0)
  • 2020-11-30 14:57

    Using this method:

    How to find UILabel's number of Lines

    You could set the label to the max height, find out how tall the text is in that label and shrink it as necessary.

    0 讨论(0)
  • 2020-11-30 14:57

    I just came to a similar problem, and solved it with a very simple solution (tested on ios 8.4, xcode 7).

    In IB (I use autolayout with some constraints):

    set UIlabel numberOfLine = 1;
    LineBrakeMode = TruncateTail
    

    In Code:

    label.numberOfLines = 2; // I can only display 2 row. 
    // I supposed you should know how many rows you can displayed.
    
    label.preferredMaxLayoutWidth = label.frame.size.width;
    [label sizeToFit];
    

    Tadaa. That's it. Note that this only work with UILabel. With UIButton, it may not work (Haven't tested).

    0 讨论(0)
提交回复
热议问题