Swift - Uibutton with Two Lines of Text

Swift - UIButton with two lines of text

There are two questions.

I was wondering if it is possible to create a UIButton with two lines
of text

This is possible through using the storyboard or programmatically.

Storyboard:

Change the 'Line Break Mode' to Character Wrap or Word Wrap and use Alt/Option + Enter key to enter a new line in the UIButton's Title field.

Sample Image

Programmatically:

override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)

btnTwoLine?.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping;
}

I need each line to have a different font size
1

The worst case is, you can use a custom UIButton class and add two labels within it.

The better way is, make use of NSMutableAttributedString. Note that,this can be achieved through only programmatically.

Swift 5:

@IBOutlet weak var btnTwoLine: UIButton?

override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)

//applying the line break mode
textResponseButton?.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping;
let buttonText: NSString = "hello\nthere"

//getting the range to separate the button title strings
let newlineRange: NSRange = buttonText.range(of: "\n")

//getting both substrings
var substring1 = ""
var substring2 = ""

if(newlineRange.location != NSNotFound) {
substring1 = buttonText.substring(to: newlineRange.location)
substring2 = buttonText.substring(from: newlineRange.location)
}

//assigning diffrent fonts to both substrings
let font1: UIFont = UIFont(name: "Arial", size: 17.0)!
let attributes1 = [NSMutableAttributedString.Key.font: font1]
let attrString1 = NSMutableAttributedString(string: substring1, attributes: attributes1)

let font2: UIFont = UIFont(name: "Arial", size: 11.0)!
let attributes2 = [NSMutableAttributedString.Key.font: font2]
let attrString2 = NSMutableAttributedString(string: substring2, attributes: attributes2)

//appending both attributed strings
attrString1.append(attrString2)

//assigning the resultant attributed strings to the button
textResponseButton?.setAttributedTitle(attrString1, for: [])
}

Older Swift

@IBOutlet weak var btnTwoLine: UIButton?

override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)

//applying the line break mode
btnTwoLine?.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping;

var buttonText: NSString = "hello\nthere"

//getting the range to separate the button title strings
var newlineRange: NSRange = buttonText.rangeOfString("\n")

//getting both substrings
var substring1: NSString = ""
var substring2: NSString = ""

if(newlineRange.location != NSNotFound) {
substring1 = buttonText.substringToIndex(newlineRange.location)
substring2 = buttonText.substringFromIndex(newlineRange.location)
}

//assigning diffrent fonts to both substrings
let font:UIFont? = UIFont(name: "Arial", size: 17.0)
let attrString = NSMutableAttributedString(
string: substring1 as String,
attributes: NSDictionary(
object: font!,
forKey: NSFontAttributeName) as [NSObject : AnyObject])

let font1:UIFont? = UIFont(name: "Arial", size: 11.0)
let attrString1 = NSMutableAttributedString(
string: substring2 as String,
attributes: NSDictionary(
object: font1!,
forKey: NSFontAttributeName) as [NSObject : AnyObject])

//appending both attributed strings
attrString.appendAttributedString(attrString1)

//assigning the resultant attributed strings to the button
btnTwoLine?.setAttributedTitle(attrString, forState: UIControlState.Normal)

}

Output

Sample Image

How do you add multi-line text to a UIButton?

For iOS 6 and above, use the following to allow multiple lines:

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
// you probably want to center it
button.titleLabel.textAlignment = NSTextAlignmentCenter; // if you want to
[button setTitle: @"Line1\nLine2" forState: UIControlStateNormal];

For iOS 5 and below use the following to allow multiple lines:

button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
// you probably want to center it
button.titleLabel.textAlignment = UITextAlignmentCenter;
[button setTitle: @"Line1\nLine2" forState: UIControlStateNormal];

2017, for iOS9 forward,

generally, just do these two things:

  1. choose "Attributed Text"
  2. on the "Line Break" popup select "Word Wrap"

2 line text UIButton

Objectivc-C

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.numberOfLines = 2;
button.titleLabel.textAlignment = NSTextAlignmentCenter; // if u need

else use this

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;
[button setTitle: @"Line1\nLine2" forState: UIControlStateNormal];

Swift

button.titleLabel!.lineBreakMode = .ByWordWrapping
button.titleLabel!.numberOfLines = 2
button.titleLabel!.textAlignment = .Center

else use this

button.titleLabel!.lineBreakMode = .ByWordWrapping
button.titleLabel!.textAlignment = .Center
button.setTitle("Line1\nLine2", forState: .Normal)

Swift3

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

UIButton with two lines of text in the title (numberOfLines=2)

Updated answer for more recent iOS versions

Since this is the accepted answer, added @Sean's answer here:

Set these properties on the titleLabel of your button.

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.numberOfLines = 2; // if you want unlimited number of lines put 0

Swift 3 and 4:

button.titleLabel?.lineBreakMode = .byWordWrapping
button.titleLabel?.numberOfLines = 2 // if you want unlimited number of lines put 0

Original answer for an older version of iOS

If you want 2 lines of text on top of your UIButton you should add a UIlabel on top of it that does precisely that.

UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 10, frame.size.width-100, 100)];
titleLabel.font = [UIFont boldSystemFontOfSize:24.0];
titleLabel.text = @"This text is very long and should get truncated at the end of the second line";
titleLabel.numberOfLines = 2;
titleLabel.lineBreakMode = UILineBreakModeTailTruncation;
[myButton addSubview:titleLabel]; //add label to button instead.

Updated for interface builder solution

Added @Borut Tomazin's answer for a more complete answer.
Updated this part again since the answer of @Borut Tomazin was improved.

You can do this much easier, with no code required. In Interface Builder set Line Break on UIButton to Word Wrap. Than you can insert multiple lines of title. Just hit Option + Return keys to make new line. You will also need to add this to the User Defined Runtime Attribute in Interface Builder:

titleLabel.textAlignment Number [1]

How would I create a UIButton with two lines of text and the first line of text being larger than the second?

the titleLabel of a UIButton is not accessible in the same ways a standalone UILabel is.
You'll want to use UIButton's setAttributedTitle:forState: method.

edit: (adding to answer line spacing question)

in this example, the attribute is NSParagraphStyleAttributeName and the value is pStyle

NSMutableParagraphStyle *pStyle = [[NSMutableParagraphStyle alloc] init];
pStyle.lineSpacing = 8;

return @{
NSParagraphStyleAttributeName : pStyle
};

Multiline Label On UIButton Swift

Use SetTitle method instead of .text , when you use .text it sets the title text but the constraints are not updated accordingly hence you need to use SetTitle method and set the adjustsFontSizeToFitWidth to true

self.syncBtn.setTitle(timeStamp, forState: UIControlState.Normal)
self.syncBtn.titleLabel?.adjustsFontSizeToFitWidth = true

Multiple Lines in UIButton

The UIButton displays it's text with a contained UILabel. The default for the contained label is to display one line of text only. This label is accessible through the titleLabel property, and anything you can do to a normal label can be done to it.

For example making it multi-lines broken by words:

ObjC:

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

Swift:

myButton.titleLabel?.numberOfLines = 0; // Dynamic number of lines
myButton.titleLabel?.lineBreakMode = .byWordWrapping;

Center two-lined Button Title

You cannot set the text alignment of UIButton in interface builder. Create and connect an IBOutlet for the said button in interface builder, and use the following code in viewDidLoad method of the view controller.

ibOutletOfButton.titleLabel.textAlignment = NSTextAlignment.Center;

I hope it helps!:-)

How can I make UILabel or UIButton with two lines , the first with one character and the second with two characters?

For multiline UIButton just set Line Break to Word Wrap and set your buttons text with the new line character (in interface builder it is ctrl+enter).

Sample Image



Related Topics



Leave a reply



Submit