我有以下代码…

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

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


当前回答

斯威夫特4.0

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

其他回答

你必须添加以下代码:

buttonLabel.titleLabel.numberOfLines = 0;

iOS7上的自动布局左对齐:

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

设置lineBreakMode为nslinebreakbywordwrapped(在IB或代码中)使按钮标签多行,但不影响按钮的帧。

如果按钮有动态标题,有一个技巧:把隐藏的UILabel与相同的字体,并把它的高度与按钮的高度与布局;当设置文本到按钮和标签和自动布局将使所有的工作。

Note

单行按钮的固有尺寸高度大于标签的固有尺寸高度,因此为了防止标签的高度缩小,标签的垂直内容拥抱优先级必须大于按钮的垂直内容压缩阻力。

基于@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
    }

}

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

[]