Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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 "..."?

like image 825
John Avatar asked Mar 22 '11 20:03

John


1 Answers

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)
like image 151
saigen Avatar answered Oct 10 '22 21:10

saigen