marketer marketer - 6 months ago 45
iOS Question

UIButton with two lines of text in the title (numberOfLines=2)

I'm trying to make a

UIButton
that has two lines of text in its titleLabel. This is the code I'm using:

UIButton *titleButton = [[UIButton alloc] initWithFrame:CGRectMake(15, 10, frame.size.width-100, 100)];
titleButton.titleLabel.font = [UIFont boldSystemFontOfSize:24.0];
[titleButton setTitle:@"This text is very long and should get truncated at the end of the second line" forState:UIControlStateNormal];
titleButton.titleLabel.lineBreakMode = UILineBreakModeTailTruncation;
titleButton.titleLabel.numberOfLines = 2;
[self addSubview:titleButton];


When I try this, the text only appears on one line. It seems the only way to achieve more than one line of text in
UIButton.titleLabel
is to set
numberOfLines=0
and use
UILineBreakModeWordWrap
. But this doesn't guarantee the text to be exactly two lines.

Using a plain
UILabel
, however, does work:

UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 10, frame.size.width-100, 100)];
titleLabel.font = [UIFont boldSystemFontOfSize:24.0];
titleLabel.text = @"This text is very long and should get truncated at the end of the second line";
titleLabel.numberOfLines = 2;
titleLabel.lineBreakMode = UILineBreakModeTailTruncation;
[self addSubview:titleLabel];


Does anyone know how to make the
UIButton
work with two lines? Is the only solution to create a separate
UILabel
to hold the text, and add it as a subview of the button?

Answer

If you want 2 lines of text on top of your UIButton you should add a UIlabel on top of it that does precisely that.

UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 10, frame.size.width-100, 100)];
titleLabel.font = [UIFont boldSystemFontOfSize:24.0];
titleLabel.text = @"This text is very long and should get truncated at the end of the second line";
titleLabel.numberOfLines = 2;
titleLabel.lineBreakMode = UILineBreakModeTailTruncation;
[myButton addSubview:titleLabel]; //add label to button instead.