Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2 line text UIButton

I have a UIButton and the text of the button is filled by a randomiser. However my problem is that sometimes the number of characters in a text is too many, leading to the button now showing the whole text.

Would it be possible to check if the characters are too many and then have it drop the rest of the text to another text line? So basically having to text lines instead of one for the UIButton?

like image 424
Mr Riksson Avatar asked Mar 26 '15 14:03

Mr Riksson


2 Answers

Objectivc-C

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.numberOfLines = 2;
button.titleLabel.textAlignment = NSTextAlignmentCenter; // if u need

else use this

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;
[button setTitle: @"Line1\nLine2" forState: UIControlStateNormal];

Swift

button.titleLabel!.lineBreakMode = .ByWordWrapping
button.titleLabel!.numberOfLines = 2
button.titleLabel!.textAlignment = .Center

else use this

button.titleLabel!.lineBreakMode = .ByWordWrapping
button.titleLabel!.textAlignment = .Center
button.setTitle("Line1\nLine2", forState: .Normal)

Swift3

buttonName.titleLabel!.lineBreakMode = .byWordWrapping
buttonName.titleLabel!.textAlignment = .center
buttonName.setTitle("Line1\nLine2", for: .normal)
like image 81
Anbu.Karthik Avatar answered Sep 18 '22 18:09

Anbu.Karthik


In the Interface Builder, change the Line Break mode to Word Wrap for the UIButton control:

enter image description here

And to center the text, make the title Attributed instead of Plain.

enter image description here

like image 36
Suragch Avatar answered Sep 20 '22 18:09

Suragch