我有以下代码...

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

...这个想法是,我可以有多线文本为按钮,但该文本总是模糊的图像的UIButton.一个通话记录显示有关子视图处的按钮表示,UILabel已经增加,但是文本本身不能被看到。这是一个错误,在UIButton或者我做错了什么?

有帮助吗?

解决方案

对于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前进

一般来说,只做这两件事:

  1. 选择"归属文字
  2. 在“换行符”上弹出窗口选择" Word Wrap"

其他提示

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

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

[]

对于IOS 6:

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

作为

UILineBreakModeWordWrap and UITextAlignmentCenter

在IOS 6之后已弃用..

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

button.titleLabel?.numberOfLines = 0

SWIFT 3

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

有一种更简单的方法:

someButton.lineBreakMode = UILineBreakModeWordWrap;

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

someButton.titleLabel.lineBreakMode = UILineBreakModeWordWrap;

使用autolayout在iOS7上左对齐:

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

首先,你应该知道UIButton里面已经有了UILabel。您可以使用– setTitle:forState:来设置它。

您的示例的问题是您需要将UILabel的 numberOfLines 属性设置为默认值1以外的值。您还应该查看 lineBreakMode 属性。

在Xcode 9.3中,您可以使用 storyboard ,如下所示

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

button.titleLabel?.textAlignment = .center

您无需使用新行(\ n)设置标题文字,如下所示

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

只需设置标题,

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

结果如下,

对于使用Xcode 4故事板的用户,可以单击按钮,在“属性检查器”下的“实用工具”窗格右侧,您将看到“换行”选项。选择Word Wrap,你应该很高兴。

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

我只想补充一点,如果您使用的是故事板,可以输入[Ctrl + Enter]强制在按钮标题字段上添加换行符。

HTH

您必须添加以下代码:

buttonLabel.titleLabel.numberOfLines = 0;

至于布伦特关于将标题UILabel作为兄弟视角的想法,我觉得这不是一个好主意。我一直在想与UILabel的交互问题,因为它的触摸事件没有通过UIButton的观点。

另一方面,使用UILabel作为UIButton的子视图,我非常容易知道触摸事件将始终传播到UILabel的超级视图。

我确实采用了这种方法,并没有注意到backgroundImage报告的任何问题。我在UIButton子类的-titleRectForContentRect:中添加了这段代码,但代码也可以放在UIButton superview的绘图例程中,在这种情况下,你应该用UIButton的变量替换对self的所有引用。

#define TITLE_LABEL_TAG 1234

- (CGRect)titleRectForContentRect:(CGRect)rect
{   
    // define the desired title inset margins based on the whole rect and its padding
    UIEdgeInsets padding = [self titleEdgeInsets];
    CGRect titleRect = CGRectMake(rect.origin.x    + padding.left, 
                                  rect.origin.x    + padding.top, 
                                  rect.size.width  - (padding.right + padding.left), 
                                  rect.size.height - (padding.bottom + padding].top));

    // save the current title view appearance
    NSString *title = [self currentTitle];
    UIColor  *titleColor = [self currentTitleColor];
    UIColor  *titleShadowColor = [self currentTitleShadowColor];

    // we only want to add our custom label once; only 1st pass shall return nil
    UILabel  *titleLabel = (UILabel*)[self viewWithTag:TITLE_LABEL_TAG];


    if (!titleLabel) 
    {
        // no custom label found (1st pass), we will be creating & adding it as subview
        titleLabel = [[UILabel alloc] initWithFrame:titleRect];
        [titleLabel setTag:TITLE_LABEL_TAG];

        // make it multi-line
        [titleLabel setNumberOfLines:0];
        [titleLabel setLineBreakMode:UILineBreakModeWordWrap];

        // title appearance setup; be at will to modify
        [titleLabel setBackgroundColor:[UIColor clearColor]];
        [titleLabel setFont:[self font]];
        [titleLabel setShadowOffset:CGSizeMake(0, 1)];
        [titleLabel setTextAlignment:UITextAlignmentCenter];

        [self addSubview:titleLabel];
        [titleLabel release];
    }

    // finally, put our label in original title view's state
    [titleLabel setText:title];
    [titleLabel setTextColor:titleColor];
    [titleLabel setShadowColor:titleShadowColor];

    // and return empty rect so that the original title view is hidden
    return CGRectZero;
}

我确实花时间写了一些关于这个的更多信息这里。在那里,我还指出了一个更短的解决方案,虽然它不太适合所有的场景,并涉及一些私人观点黑客攻击。还有,你可以下载一个可以使用的UIButton子类。

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

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

效果很好。

添加使用配置文件如Plist,你需要使用CDATA来编写多线标题,如下所示:

<string><![CDATA[Line1
Line2]]></string>

设置lineBreakMode到NSLineBreakByWordWrapping(无论是在IB或代码),使按钮标签多,但不影响按钮的框架。

如果按钮具有动态标题中,有一个窍门:把隐藏UILabel用相同的字体,并配合它的高度键的高度与布局;当设置文本按钮和标签和自动版式将使所有工作。

注意到

固有的高度的一个线按钮超过标签的,因此对防止标签的高度收缩,这是垂直的内容拥抱的优先事项必须是大于按钮的垂直的内容压缩的阻力。

如果您使用自动布局。

button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.numberOfLines = 2

我遇到了自动布局的问题,启用多行后结果是这样的:

所以 titleLabel 大小不会影响按钮大小
我添加了基于 contentEdgeInsets Constraints (在这种情况下,contentEdgeInsets为(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)
            ])
    }

}

现在,如果您真的需要在界面构建器中根据具体情况访问此类事物,您可以使用这样的简单扩展来实现:

extension UIButton {
    @IBInspectable var numberOfLines: Int {
        get { return titleLabel?.numberOfLines ?? 1 }
        set { titleLabel?.numberOfLines = newValue }
    }
}

然后你可以简单地将numberOfLines设置为任何UIButton或UIButton子类的属性,就像它是一个标签一样。对于许多其他通常不可访问的值也是如此,例如视图图层的角半径,或者它所投射的阴影的属性。

滚动你自己的按钮类。从长远来看,它是迄今为止最好的解决方案。 UIButton和其他UIKit类在如何自定义它们方面非常严格。

self.btnError.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping

self.btnError.titleLabel?.textAlignment = .center

self.btnError.setTitle("Title", for: .normal)

swift 4.0

btn.titleLabel?.lineBreakMode = .byWordWrapping
btn.titleLabel?.textAlignment = .center
btn.setTitle( "Line1\nLine2", for: .normal)

我在 jessecurry的回答 /master/STAControls/STAControls/Button/STAButton.h“rel =”nofollow noreferrer“> STAButton 是我的 STAControls 开源库。我目前在我正在开发的其中一个应用程序中使用它,它可以满足我的需求。请随意打开有关如何改进或向我发送拉取请求的问题。

Swift 5.0 Xcode 10.2

SharedClass 示例写一次并使用每个器皿

这是您的共享类(就像您使用所有组件属性一样)

import UIKit

class SharedClass: NSObject {

     static let sharedInstance = SharedClass()

     private override init() {

     }
  }

//UIButton extension
extension UIButton {
     //UIButton properties
     func btnMultipleLines() {
         titleLabel?.numberOfLines = 0
         titleLabel?.lineBreakMode = .byWordWrapping
         titleLabel?.textAlignment = .center        
     }
}

在您的 ViewController 调用中

button.btnMultipleLines()//This is your button

虽然将子视图添加到控件中是可以的,但是不能保证它实际上可以正常工作,因为控件可能不会指望它在那里并因此可能表现不佳。如果您可以使用它,只需将标签添加为按钮的同级视图并设置其框架,使其与按钮重叠;只要它设置为显示在按钮顶部,按钮可以做的任何事都不会使它模糊不清。

换句话说:

[button.superview addSubview:myLabel];
myLabel.center = button.center;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top