Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add multi-line text to a UIButton?

I have the following code...

UILabel *buttonLabel = [[UILabel alloc] initWithFrame:targetButton.bounds]; buttonLabel.text = @"Long text string"; [targetButton addSubview:buttonLabel]; [targetButton bringSubviewToFront:buttonLabel]; 

...the idea being that I can have multi-line text for the button, but the text is always obscured by the backgroundImage of the UIButton. A logging call to show the subviews of the button shows that the UILabel has been added, but the text itself cannot be seen. Is this a bug in UIButton or am I doing something wrong?

like image 477
Owain Hunt Avatar asked Mar 03 '09 00:03

Owain Hunt


People also ask

How do I add multiple lines to text?

vim Inserting text Insert text into multiple lines at once Press Ctrl + v to enter into visual block mode. Use ↑ / ↓ / j / k to select multiple lines. Press Shift + i and start typing what you want. After you press Esc , the text will be inserted into all the lines you selected.

How do I add text to UIButton?

Programmatically. To make a multi-line text in UIButton, you insert a new line character ( \n ) wherever you want in button title and set lineBreakMode to byWordWrapping . You can adjust text alignment with . textAlignment .

What is UIButton Swift?

A control that executes your custom code in response to user interactions.


1 Answers

For iOS 6 and above, use the following to allow multiple lines:

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping; // you probably want to center it button.titleLabel.textAlignment = NSTextAlignmentCenter; // if you want to  [button setTitle: @"Line1\nLine2" forState: UIControlStateNormal]; 

For iOS 5 and below use the following to allow multiple lines:

button.titleLabel.lineBreakMode = UILineBreakModeWordWrap; // you probably want to center it button.titleLabel.textAlignment = UITextAlignmentCenter; [button setTitle: @"Line1\nLine2" forState: UIControlStateNormal]; 

2017, for iOS9 forward,

generally, just do these two things:

  1. choose "Attributed Text"
  2. on the "Line Break" popup select "Word Wrap"
like image 167
jessecurry Avatar answered Oct 04 '22 10:10

jessecurry