我有以下代码…

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

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


当前回答

对于那些使用Xcode 4的故事板的人,你可以点击按钮,在右边的属性检查器下的实用工具窗格,你会看到一个换行选项。选择“换行”,应该就可以了。

其他回答

重申一下Roger Nolan的建议,但使用显式代码,这是一般的解决方案:

button.titleLabel?.numberOfLines = 0

斯威夫特3

button.titleLabel?.lineBreakMode = .byWordWrapping
button.titleLabel?.textAlignment = .center  
button.setTitle("Button\nTitle",for: .normal)

除了@Amir Khorsandi的回答。

你可能只需要添加uibutton.TitleLabel.TranslatesAutoresizingMaskIntoConstraints = false; 当你把它添加到uibutton本身时。(对不起,我认为你可以很容易地翻译c#)。所以uibutton。LineBreakMode = UILineBreakMode.WordWrap; 将启用多行文本。因为当你想要在按钮中添加图像或其他东西时,这些限制会给你带来问题。

滚动您自己的按钮类。从长远来看,这是目前为止最好的解决方案。UIButton和其他UIKit类在如何自定义它们方面是非常受限的。

它工作得很完美。

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

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