我有以下代码…

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

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


当前回答

有一个更简单的方法:

someButton.lineBreakMode = UILineBreakModeWordWrap;

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

someButton.titleLabel.lineBreakMode = UILineBreakModeWordWrap;

其他回答

除了@Amir Khorsandi的回答。

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

它工作得很完美。

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

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

基于@Amir Khorsandi的回答-但如果你有一个带有图像的按钮:

extension UIButton {

    func enableMultiline() {
        setContentHuggingPriority(.defaultLow, for: .vertical) // high hugging priority could squeeze the button to 1 line
        titleLabel?.numberOfLines = 0
        titleLabel?.setContentCompressionResistancePriority(.required, for: .vertical)
        titleLabel?.topAnchor.constraint(greaterThanOrEqualTo: topAnchor).isActive = true
        titleLabel?.bottomAnchor.constraint(lessThanOrEqualTo: bottomAnchor).isActive = true
        imageView?.setContentCompressionResistancePriority(.required, for: .horizontal) // otherwise image could be squeezed
    }

}

斯威夫特4.0

btn.titleLabel?.lineBreakMode = .byWordWrapping
btn.titleLabel?.textAlignment = .center
btn.setTitle( "Line1\nLine2", for: .normal)

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

[]