我有以下代码…

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

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


当前回答

添加按钮约束和子视图。这就是我如何在我的项目,让我们说它更容易这样做。我99%的时间都是通过编程来完成的。因为这对我来说容易多了。故事板有时真的会有bug [1]: https://i.stack.imgur.com/5ZSwl.png

其他回答

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

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

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

iOS7上的自动布局左对齐:

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentLeft;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

有一个更简单的方法:

someButton.lineBreakMode = UILineBreakModeWordWrap;

(适用于iOS 3及更高版本:)

someButton.titleLabel.lineBreakMode = UILineBreakModeWordWrap;

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

[]

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

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