我有以下代码…

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上使用自动布局,你可能还需要设置preferredmaxlayoutidth属性:

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

其他回答

iOS7上的自动布局左对齐:

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentLeft;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

在2021年的iOS 15中,苹果首次通过UIButton正式支持多行UIButton。配置API。

UIButton。配置 一种配置,用于指定按钮及其内容的外观和行为。

这个新的API在什么是新的UIKit以及会话中进行了探索:

满足UIKit按钮系统 每个应用程序都使用按钮。在iOS 15中,你可以采用更新的样式来创建华丽的按钮,轻松融入你的界面。我们将探索使创建不同类型的按钮更容易的功能,学习如何提供更丰富的交互,并发现如何在使用Mac Catalyst时获得出色的按钮。 https://developer.apple.com/videos/play/wwdc2021/10064/

它工作得很完美。

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

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

如果你想添加一个带有多行居中标题的按钮,请为该按钮设置界面生成器的设置:

[]

有一个更简单的方法:

someButton.lineBreakMode = UILineBreakModeWordWrap;

(适用于iOS 3及更高版本:)

someButton.titleLabel.lineBreakMode = UILineBreakModeWordWrap;