我有以下代码…

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

...这个想法是,我可以有多行文本的按钮,但文本总是被UIButton的backgroundImage掩盖。显示按钮子视图的日志调用显示UILabel已添加,但文本本身无法看到。这是UIButton的bug还是我做错了什么?


当前回答

对于iOS 6及以上版本,使用以下命令允许多行:

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

对于iOS 5及以下版本,使用以下命令允许多行:

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

2017年,对于iOS9,

一般来说,你只需要做以下两件事:

选择“属性文本” 在“换行”窗口选择“换行”

其他回答

首先,你应该知道UIButton里面已经有一个UILabel。你可以使用-setTitle:forState:来设置它。

您的示例的问题在于,您需要将UILabel的numberolines属性设置为其默认值1以外的值。您还应该检查lineBreakMode属性。

它工作得很完美。

添加到使用这个配置文件,如Plist,你需要使用CDATA来写多行标题,像这样:

<string><![CDATA[Line1
Line2]]></string>

在Xcode 9.3中,你可以像下面这样使用storyboard,

你需要设置按钮标题textAlignment到中心

button.titleLabel ?。textAlignment = .center

你不需要像下面这样用新行(\n)设置标题文本,

巴顿。setTitle(“祝\ nAnswer”,为:正常的。)

简单设置标题,

按钮。setTitle(“好答案”,为:.normal)

这是结果,

如果你在iOS 6上使用自动布局,你可能还需要设置preferredmaxlayoutidth属性:

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;
button.titleLabel.preferredMaxLayoutWidth = button.frame.size.width;

对于IOS 6:

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

As

UILineBreakModeWordWrap and UITextAlignmentCenter

在ios6以后已弃用。