ios 如何将多行文本添加到 UIButton?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/604632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:43:14  来源:igfitidea点击:

How do you add multi-line text to a UIButton?

ioscocoa-touchuibuttonuikit

提问by Owain Hunt

I have the following code...

我有以下代码...

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

...the idea being that I can have multi-line text for the button, but the text is always obscured by the backgroundImage of the UIButton. A logging call to show the subviews of the button shows that the UILabel has been added, but the text itself cannot be seen. Is this a bug in UIButton or am I doing something wrong?

...的想法是我可以为按钮设置多行文本,但文本总是被 UIButton 的 backgroundImage 遮挡。显示按钮子视图的日志调用显示已添加 UILabel,但无法看到文本本身。这是 UIButton 中的错误还是我做错了什么?

回答by jessecurry

For iOS 6 and above, use the following to allow multiple lines:

对于 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];

For iOS 5 and below use the following to allow multiple lines:

对于 iOS 5 及更低版本,请使用以下内容来允许多行:

button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
// you probably want to center it
button.titleLabel.textAlignment = UITextAlignmentCenter;
[button setTitle: @"Line1\nLine2" forState: UIControlStateNormal];

2017, for iOS9 forward,

2017年,为iOS9前进

generally, just do these two things:

通常,只需做以下两件事:

  1. choose "Attributed Text"
  2. on the "Line Break" popup select "Word Wrap"
  1. 选择“属性文本”
  2. 在“换行符”弹出窗口中选择“自动换行”

回答by Adam Waite

The selected answer is correct but if you prefer to do this sort of thing in Interface Builder you can do this:

所选答案是正确的,但如果您更喜欢在 Interface Builder 中执行此类操作,则可以执行以下操作:

pic

图片

回答by user5440039

If you want to add a button with the title centered with multiple lines, set your Interface Builder's settings for the button:

如果要添加标题以多行居中的按钮,请为该按钮设置界面生成器的设置:

[here]

[ 这里]

回答by NiKKi

For IOS 6 :

对于 IOS 6:

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;

As

作为

UILineBreakModeWordWrap and UITextAlignmentCenter

are deprecated in IOS 6 onwards..

在 IOS 6 以后不推荐使用..

回答by baudot

To restate Roger Nolan's suggestion, but with explicit code, this is the general solution:

重申 Roger Nolan 的建议,但使用明确的代码,这是通用的解决方案:

button.titleLabel?.numberOfLines = 0

回答by Md. Ibrahim Hassan

SWIFT 3

斯威夫特 3

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

回答by Nazrul Islam

In Xcode 9.3 you can do it by using storyboardlike below,

在 Xcode 9.3 中,您可以使用如下所示的故事板来完成,

enter image description here

在此处输入图片说明

You need to set button title textAlignment to center

您需要将按钮标题 textAlignment 设置为居中

button.titleLabel?.textAlignment = .center

button.titleLabel?.textAlignment = .center

You don't need to set title text with new line (\n) like below,

您不需要像下面这样使用换行符 (\n) 设置标题文本,

button.setTitle("Good\nAnswer",for: .normal)

button.setTitle("Good\nAnswer",for: .normal)

Simply set title,

只需设置标题,

button.setTitle("Good Answer",for: .normal)

button.setTitle("Good Answer",for: .normal)

Here is the result,

这是结果,

enter image description here

在此处输入图片说明

回答by neoneye

Left align on iOS7 with autolayout:

在 iOS7 上使用自动布局左对齐:

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

回答by Valerii Hiora

There is a much easier way:

有一个更简单的方法:

someButton.lineBreakMode = UILineBreakModeWordWrap;

(Edit for iOS 3 and later:)

(针对 iOS 3 及更高版本进行编辑:)

someButton.titleLabel.lineBreakMode = UILineBreakModeWordWrap;

回答by Amir Khorsandi

I had an issue with auto-layout, after enabling multi-line the result was like this:
enter image description here
so the titleLabelsize doesn't affect the button size
I've added Constraintsbased on contentEdgeInsets(in this case contentEdgeInsets was (10, 10, 10, 10)
after calling makeMultiLineSupport():
enter image description here
hope it helps you (swift 5.0):

我遇到了自动布局问题,启用多行后结果是这样的: 所以大小不会影响 我基于添加的按钮大小(在这种情况下 contentEdgeInsets 是 (10, 10, 10, 10 ) 调用后: 希望对您有所帮助(swift 5.0):
在此处输入图片说明
titleLabel
ConstraintscontentEdgeInsets
makeMultiLineSupport()
在此处输入图片说明

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)
            ])
    }

}