我有以下代码…

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

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


当前回答

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

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

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

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

其他回答

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

换句话说:

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

对于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,

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

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

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

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

对于IOS 6:

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

As

UILineBreakModeWordWrap and UITextAlignmentCenter

在ios6以后已弃用。

在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