我有以下代码…

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/

其他回答

重申一下Roger Nolan的建议,但使用显式代码,这是一般的解决方案:

button.titleLabel?.numberOfLines = 0

你必须添加以下代码:

buttonLabel.titleLabel.numberOfLines = 0;

Swift 5,用于UIButton中的多行文本

  let button = UIButton()
  button.titleLabel?.lineBreakMode = .byWordWrapping
  button.titleLabel?.textAlignment = .center
  button.titleLabel?.numberOfLines = 0 // for Multi line text
self.btnError.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping

self.btnError.titleLabel?.textAlignment = .center

self.btnError.setTitle("Title", for: .normal)

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

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