Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap a text on a UIButton in swift

I try to wrap a text on a button as follow:

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);

I can see the button on the device, but I don't see any text.

What am I doing wrong ? Or can this be done without adding a label to a button ? Thanks for helping.

Illustration. It looks like :

enter image description here

When just doing:

nextButton.setTitle("this is a very very long text", forState: UIControlState.Normal)
like image 299
mcfly soft Avatar asked Apr 24 '15 12:04

mcfly soft


People also ask

How do you make a UIButton multiline?

To make a multi-line text in UIButton, you insert a new line character ( \n ) wherever you want in button title and set lineBreakMode to byWordWrapping . You can adjust text alignment with . textAlignment .

What is UIButton Swift?

A control that executes your custom code in response to user interactions.


1 Answers

You need to write text in the setTitle method:

nextButton.setTitle("This is the very very long text!", forState: UIControlState.Normal)

Set the number of lines and wrap mode to the title label:

nextButton.titleLabel.numberOfLines = 0; // Dynamic number of lines
nextButton.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;

Update to Swift 4

nextButton.titleLabel.numberOfLines = 0; // Dynamic number of lines
nextButton.titleLabel.lineBreakMode = NSLineBreakMode.byWordWrapping;
like image 114
Sohil R. Memon Avatar answered Sep 22 '22 16:09

Sohil R. Memon