我有以下代码…

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; 将启用多行文本。因为当你想要在按钮中添加图像或其他东西时,这些限制会给你带来问题。

其他回答

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

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

[]

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

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

斯威夫特3

button.titleLabel?.lineBreakMode = .byWordWrapping
button.titleLabel?.textAlignment = .center  
button.setTitle("Button\nTitle",for: .normal)

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

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