开发者

UIButton multi-line text with tail truncation

I have found similar questions that ask how to have multi-line text on a UIButton, and the solution is to set

[myUIButton.titleLabel setLineBreakMode:UILineBreakModeWordWrap];
[myUIButton setTitle:myTitle forState:UIControlStateNormal];

However, this results in the button title taking up many lines.开发者_Go百科 I have tried restricting the number of lines using

[myUIButton.titleLabel setNumberOfLines:2];

but this does not have any affect on the resulting number of lines.

Is there a way to limit the lines word wrapped to 2 lines on the UIButton title, and then have the tail truncated with "..."?


By setting lineBreakMode before numberOfLines your desired result can be achieved… This is because lineBreakMode seems to cancel out numberOfLines set hence we are doing it in this order.

Objective-C:

[button.titleLabel setLineBreakMode: UILineBreakModeTailTruncation];
[button.titleLabel setNumberOfLines:2];
[button setTitle:myTitle forState:UIControlStateNormal];

Swift 3: from Xcode 6 and above UILineBreakMode is replaced by NSLineBreakMode

button.titleLabel?.lineBreakMode = NSLineBreakMode.byTruncatingTail
button.titleLabel?.numberOfLines = 2
button.setTitle(myTitle, for: UIControlState.normal)


I know its been a while since the question was first asked, but I came across the same problem and endend up with a simple but functional solution after considering the answer posted here.

The solution that worked for me was the following:

// Set the line break mode to word wrap so it won't truncate automatically
[button.titleLabel setLineBreakMode: UILineBreakModeWordWrap];

// Call a method that truncates the string I want to use
[button setTitle:[self truncateString:myButtonText] forState:UIControlStateNormal];

And the truncateString method:

- (NSString *)truncateString:(NSString *)stringToTruncate
{
    if ([stringToTruncate length] > 50)
        stringToTruncate = [[stringToTruncate substringToIndex:50] stringByAppendingString:@"..."];

    return  stringToTruncate;
}

So basically I calculated the number of characters that would work for my button, and then forced any string longer than that to have the '...' at the end. I know its not the ideal solution but I guess it can work for some of us, I hope it helps.


[button.titleLabel setNumberOfLines:2];
[button.titleLabel setLineBreakMode: UILineBreakModeTailTruncation];
[button setTitle:myTitle forState:UIControlStateNormal];

it does it for me! :D cheers!!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜