我有以下代码…

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

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


当前回答

要修复按钮title标签的间距,在setTitle之前设置titleEdgeInsets和其他属性:

    let button = UIButton()
    button.titleLabel?.lineBreakMode = .byWordWrapping
    button.titleLabel?.numberOfLines = 0
    button.titleEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 20, right: 20)
    button.setTitle("Dummy button with long long long long long long long long title", for: .normal)

附注:我测试设置titleLabel?textAlignment是不必要的,标题对齐在.natural。

其他回答

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

}

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

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

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

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

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

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

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

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

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

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