如何在swift中包装UIButton上的文本

mcf*_*oft 4 uibutton uilabel ios swift

我尝试将文本包装在按钮上,如下所示:

nextButton=UIButton(frame: CGRectMake(buttonHWidth, textHeigth, buttonHWidth, buttonHeigth));

        nextButton.backgroundColor = UIColor.lightGrayColor()
        nextButton.setTitle("", forState: UIControlState.Normal)
        nextButton.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
        nextButton.tag = 22;


        label_nextButton = UILabel(frame: CGRectMake(buttonHWidth, textHeigth, buttonHWidth, buttonHeigth));
        label_nextButton.textAlignment = NSTextAlignment.Center;
        label_nextButton.numberOfLines = 2;
        label_nextButton.font = UIFont.systemFontOfSize(16.0);
        label_nextButton.text = "Prss next Press next";
        label_nextButton.textColor=UIColor.blackColor();

        nextButton.addSubview(label_nextButton);
        self.view.addSubview(nextButton);
Run Code Online (Sandbox Code Playgroud)

我可以看到设备上的按钮,但我看不到任何文字.

我究竟做错了什么 ?或者可以在不向按钮添加标签的情况下完成此操作?谢谢你的帮助.

插图.看起来像 :

在此输入图像描述

刚做的时候:

nextButton.setTitle("this is a very very long text", forState: UIControlState.Normal)
Run Code Online (Sandbox Code Playgroud)

Soh*_*mon 10

您需要在setTitle方法中编写文本:

nextButton.setTitle("This is the very very long text!", forState: UIControlState.Normal)
Run Code Online (Sandbox Code Playgroud)

将行数和换行模式设置为标题标签:

nextButton.titleLabel.numberOfLines = 0; // Dynamic number of lines
nextButton.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
Run Code Online (Sandbox Code Playgroud)

更新到Swift 4

nextButton.titleLabel.numberOfLines = 0; // Dynamic number of lines
nextButton.titleLabel.lineBreakMode = NSLineBreakMode.byWordWrapping;
Run Code Online (Sandbox Code Playgroud)