mcfly soft
mcfly soft

Reputation: 11665

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)

Upvotes: 8

Views: 12525

Answers (2)

Sohel L.
Sohel L.

Reputation: 9540

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;

Upvotes: 17

Tamás Králik
Tamás Králik

Reputation: 201

Swift 4

To shorten text by replacing the middle of the text with "..." you should use NSLineBreakMode.byWordWrapping:

nextButton.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping

To shorten the text by replacing the end of the text with "..." you should use NSLineBreakMode.byTruncatingTail:

nextButton.titleLabel?.lineBreakMode = NSLineBreakMode.byTruncatingTail

To see the full list of available wrapping modes check out the NSLineBreakMode documentation: https://developer.apple.com/documentation/appkit/nslinebreakmode

Upvotes: 4

Related Questions