23

I've been wondering, is there a nice way to make UIButtons with multi-line titleLabel in Interface Builder? I've found none and puttin a separate UILabel on top of each button and tracking it's color on press and other events is not very straightforward.

Maybe there are better alternatives done in code if there's no such way in IB?

Sergey Grischyov
  • 11,995
  • 20
  • 81
  • 120

4 Answers4

59

Code:

To allow multiple line you can use:

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

In iOS 6, UILineBreakModeWordWrap and UITextAlignmentCenter are deprecated, so use:

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;

Interface Builder:

  • In interface builder select UIButton
  • on the right side Utilities pane under Attributes Inspector, you'll see an option for Line Break
  • Choose Word Wrap
Mrunal
  • 13,982
  • 6
  • 52
  • 96
  • 1
    @AsenKasimov what's your problem? The original answer/question has nothing to do with Storyboards – Sergey Grischyov Jun 24 '16 at 10:12
  • 1
    The problem is that the question which I think is the same as the original contains more answers and during the years more info was added. Like this one http://stackoverflow.com/a/33255117/466577 – Ahmed Ahmedov Jun 24 '16 at 10:27
4

You can do solely in Interface Builder a couple ways.

  • First by simply setting the wrap feature. This offers limited customizability though.
  • For more customizability, change the "Plain Text" to "Attributed Text" and then you can do most things without any code.
DBD
  • 23,075
  • 12
  • 60
  • 84
3

In the case you are using only plain XCode 9.4:

Set Line Break to any option (to enable numberOfLines) in the Attributes inspector:

The first step in XCode

Then you can set KeyPath as

titleLabel.numberOfLines

in the Identity inspector:

The second step in XCode

Darius Miliauskas
  • 3,391
  • 4
  • 35
  • 53
0

Just to mention if one does not want word wrap but still want to achieve multi line title on a UIButton it can be done by setting lineBreakMode before numberOfLines, This is because lineBreakMode seems to cancel out numberOfLines set hence we are doing it in this order.

Swift:

button.titleLabel?.lineBreakMode = NSLineBreakMode.byTruncatingTail

button.titleLabel?.numberOfLines = 2

button.setTitle(myTitle, for: UIControlState.normal)

Community
  • 1
  • 1
saigen
  • 306
  • 2
  • 8