我有以下代码…

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

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


当前回答

现在,如果你真的需要在接口构建器中逐个访问这类东西,你可以用一个简单的扩展,像这样:

extension UIButton {
    @IBInspectable var numberOfLines: Int {
        get { return titleLabel?.numberOfLines ?? 1 }
        set { titleLabel?.numberOfLines = newValue }
    }
}

然后你可以简单地将numberolines设置为任何UIButton或UIButton子类的属性,就像它是一个标签一样。同样的道理也适用于其他一大堆通常无法访问的值,比如视图层的角半径,或者它所投射的阴影的属性。

其他回答

在2021年的iOS 15中,苹果首次通过UIButton正式支持多行UIButton。配置API。

UIButton。配置 一种配置,用于指定按钮及其内容的外观和行为。

这个新的API在什么是新的UIKit以及会话中进行了探索:

满足UIKit按钮系统 每个应用程序都使用按钮。在iOS 15中,你可以采用更新的样式来创建华丽的按钮,轻松融入你的界面。我们将探索使创建不同类型的按钮更容易的功能,学习如何提供更丰富的交互,并发现如何在使用Mac Catalyst时获得出色的按钮。 https://developer.apple.com/videos/play/wwdc2021/10064/

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

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

对于iOS 6及以上版本,使用以下命令允许多行:

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
// you probably want to center it
button.titleLabel.textAlignment = NSTextAlignmentCenter; // if you want to 
[button setTitle: @"Line1\nLine2" forState: UIControlStateNormal];

对于iOS 5及以下版本,使用以下命令允许多行:

button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
// you probably want to center it
button.titleLabel.textAlignment = UITextAlignmentCenter;
[button setTitle: @"Line1\nLine2" forState: UIControlStateNormal];

2017年,对于iOS9,

一般来说,你只需要做以下两件事:

选择“属性文本” 在“换行”窗口选择“换行”

虽然向控件添加子视图是可以的,但不能保证它会实际工作,因为控件可能不会期望它在那里,因此可能表现不佳。如果你可以摆脱它,只需添加标签作为按钮的兄弟姐妹视图,并设置它的框架,使其重叠按钮;只要它被设置为显示在按钮的顶部,按钮所做的任何事情都不会使它模糊。

换句话说:

[button.superview addSubview:myLabel];
myLabel.center = button.center;

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

}