Change the default value to "..." at the end of the text if the contents of the UILabel do not fit

I have a UILabel in my iPhone project that has a fixed width and height, but the content may vary depending on what the user is looking for. Sometimes the text is large for UILabel, and just then the line: "..." is added to the end of the line. I wonder if I can change this line to something else, for example: '(more)'.

Thank!

+5
source share
3 answers

Unfortunately, it seems that this option is not enabled on iOS in accordance with this similar question: How to change truncated characters in UILabel?

, , . , , , , . .

:

, . sizeWithFont: forWidth: lineBreakMode: UIKit NSString, . .

+1

, , ...

- (void)setText:(UILabel *)label withText:(NSString *)text andTruncationSuffix:(NSString *)truncationSuffix {

    // just set the text if it fits using the minimum font
    //
    CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:label.minimumFontSize]];
    if (size.width <= label.bounds.size.width) {
        label.text = text;
        return;
    }

    // build a truncated version of the text (using the custom truncation text)
    // and shrink the truncated text until it fits
    NSInteger lastIndex = text.length;
    CGFloat width = MAXFLOAT;

    NSString *subtext, *ellipticalText;

    while (lastIndex > 0 && width > label.bounds.size.width)  {
        subtext = [text substringToIndex:lastIndex];
        ellipticalText = [subtext stringByAppendingString:truncationSuffix];
        width = [ellipticalText sizeWithFont:[UIFont systemFontOfSize:label.minimumFontSize]].width;
        lastIndex--;
    }
    label.text = ellipticalText;
}

:

[self setText:self.label withText:@"Now is the time for all good men to come to the aid of their country" andTruncationSuffix:@" more"];

, UILabel, , setText: , truncatedSuffix.

+1

If you are using iOS version> 8.0, you can use ResponsiveLabel . Here you can provide a custom truncation token, as well as define actions to make it available.

NSString *expansionToken = @"Read More ...";
NSString *str = @"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc]initWithString:kExpansionToken attributes:@{NSForegroundColorAttributeName:[UIColor blueColor],NSFontAttributeName:self.customLabel.font}];
[self.customLabel setAttributedTruncationToken:attribString withAction:^(NSString *tappedString) {
 NSLog(@"Tap on truncation text");
}];
[self.customLabel setText:str withTruncation:YES];
+1
source

All Articles