我有以下代码…

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

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


当前回答

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

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

其他回答

有一个更简单的方法:

someButton.lineBreakMode = UILineBreakModeWordWrap;

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

someButton.titleLabel.lineBreakMode = UILineBreakModeWordWrap;

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

button.titleLabel?.numberOfLines = 0

在Swift 5.0和Xcode 10.2中

//UIButton extension
extension UIButton {
     //UIButton properties
     func btnMultipleLines() {
         titleLabel?.numberOfLines = 0
         titleLabel?.lineBreakMode = .byWordWrapping
         titleLabel?.textAlignment = .center        
     }
}

在你的ViewController调用中

button.btnMultipleLines()//This is your button

你必须添加以下代码:

buttonLabel.titleLabel.numberOfLines = 0;

斯威夫特3

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