Search code examples
iosuibuttonautolayoutline-breaks

UIButton with Linebreak and Autolayout


I have a UIButton which I set it's text within the app, however the text is too long so I'd like to have the UIButton text do a linebreak and continue on the next row.

And it has to work with AutoLayout.

I've managed to to so with a UILabel with this code:

label.numberOfLines = 0;
label.preferredMaxLayoutWidth = 300.0;

However when I apply it to a button like this:

button.titleLabel.preferredMaxLayoutWidth = 200.0;
button.titleLabel.numberOfLines = 0;

it doesn't seem to work.

That code is placed in the viewDidLoad like so:

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
label.numberOfLines = 0;
label.preferredMaxLayoutWidth = 300.0;

button.titleLabel.preferredMaxLayoutWidth = 200.0;
button.titleLabel.numberOfLines = 0; }

And then I set the button text with an IBAction like so

-(IBAction)labelMake:(id)sender {

label.text = [NSString stringWithFormat: @"Test to see if label linebreaks"];

button.titleLabel.text = [NSString stringWithFormat: @"Test to see if button text linebreaks"];}

Solution

  • Just setup the UIButton with:

    button.titleLabel.numberOfLines = 0;
    button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
    

    And set the text with:

    [button setTitle:@"This is a long text \nspanning multiple lines\nAnd there would be A LOT MORE" forState:UIControlStateNormal];