我有以下代码…

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:

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;

As

UILineBreakModeWordWrap and UITextAlignmentCenter

在ios6以后已弃用。

其他回答

如果你在iOS 6上使用自动布局,你可能还需要设置preferredmaxlayoutidth属性:

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

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

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

Note

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

我有一个自动布局的问题,启用多行后的结果是这样的: 所以titleLabel大小不影响按钮大小 我添加了基于contenttedgeinsets的约束(在这种情况下,contenttedgeinsets是(10,10,10,10) 调用makeMultiLineSupport()后: 希望它能帮助你(swift 5.0):

extension UIButton {

    func makeMultiLineSupport() {
        guard let titleLabel = titleLabel else {
            return
        }
        titleLabel.numberOfLines = 0
        titleLabel.setContentHuggingPriority(.required, for: .vertical)
        titleLabel.setContentHuggingPriority(.required, for: .horizontal)
        addConstraints([
            .init(item: titleLabel,
                  attribute: .top,
                  relatedBy: .greaterThanOrEqual,
                  toItem: self,
                  attribute: .top,
                  multiplier: 1.0,
                  constant: contentEdgeInsets.top),
            .init(item: titleLabel,
                  attribute: .bottom,
                  relatedBy: .greaterThanOrEqual,
                  toItem: self,
                  attribute: .bottom,
                  multiplier: 1.0,
                  constant: contentEdgeInsets.bottom),
            .init(item: titleLabel,
                  attribute: .left,
                  relatedBy: .greaterThanOrEqual,
                  toItem: self,
                  attribute: .left,
                  multiplier: 1.0,
                  constant: contentEdgeInsets.left),
            .init(item: titleLabel,
                  attribute: .right,
                  relatedBy: .greaterThanOrEqual,
                  toItem: self,
                  attribute: .right,
                  multiplier: 1.0,
                  constant: contentEdgeInsets.right)
            ])
    }

}

如果你使用自动布局。

button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.numberOfLines = 2

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