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 :
When just doing:
nextButton.setTitle("this is a very very long text", forState: UIControlState.Normal)
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 .
A control that executes your custom code in response to user interactions.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With