我有以下代码…

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

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


当前回答

除了@Amir Khorsandi的回答。

你可能只需要添加uibutton.TitleLabel.TranslatesAutoresizingMaskIntoConstraints = false; 当你把它添加到uibutton本身时。(对不起,我认为你可以很容易地翻译c#)。所以uibutton。LineBreakMode = UILineBreakMode.WordWrap; 将启用多行文本。因为当你想要在按钮中添加图像或其他东西时,这些限制会给你带来问题。

其他回答

我有一个自动布局的问题,启用多行后的结果是这样的: 所以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)
            ])
    }

}

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

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

如果你想添加一个带有多行居中标题的按钮,请为该按钮设置界面生成器的设置:

[]

这里的答案告诉你如何实现多行按钮标题编程。

我只是想添加,如果你正在使用故事板,你可以输入[Ctrl+Enter]强制在按钮标题字段换行。

HTH

要修复按钮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。