UIButton title alignment and multiline support
Solution 1
Here's the code to do the UIButton alignment in code too: -
[myButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
Solution 2
To set the alignment of a UIButton
, look in the Attributes Inspector in Interface Builder for the button. There's a section called Alignment. Set it to left. Or right, or whatever you want.
To do it in code, use the contentHorizontalAlignment
property of UIControl
. You can set it to any of these properties:
UIControlContentHorizontalAlignmentCenter
UIControlContentHorizontalAlignmentLeft
UIControlContentHorizontalAlignmentRight
UIControlContentHorizontalAlignmentFill
[myButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
None of these options look particularly good (as you can see above), and you might have might have more luck using the contentEdgeInsets
property of UIButton
to reposition the content.
To set a multiline title on a UIButton
, check this forum post which describes changing the button label.
Or you can use this code to quickly make a 2 line button:
myButton.titleLabel.textAlignment = UITextAlignmentCenter;
myButton.titleLabel.lineBreakMode = UILineBreakModeCharacterWrap;
[myButton setTitle:@"Siegfried\nRoy" forState:UIControlStateNormal];
Raju, don't forget to mark questions as accepted.
Solution 3
Actually, you can set the lineBreakMode
to UILineBreakModeWordWrap
or UILineBreakModeCharacterWrap
. This breaks the text into multiple lines if necessary.
Solution 4
Try this
myButton.titleLabel.textAlignment = UITextAlignmentLeft;
myButton.titleLabel.lineBreakMode = UILineBreakModeCharacterWrap;
myButton.titleLabel.numberOfLines = 0;
Solution 5
To add a Paragraph effect you can change the size of title.
Raju
Updated on July 05, 2022Comments
-
Raju almost 2 years
How do I set the title of a
UIButton
to be left-aligned, and how can I show multiple lines of text in aUIButton
? -
Rog almost 15 yearsyou didn't get it enough to mark some of your questions answered ;-)
-
ıɾuǝʞ almost 12 years
numberOfLines
works on iOS5, but still need to setlineBreakMode
for iOS 4. -
AndrewCr over 11 yearsNote that when setting the title, it's important to use the message that specifies the UIControlState. If you just set it like a property, the label won't resize for the new text. See: stackoverflow.com/questions/4576331/…
-
nevan king over 11 years@AndrewCr Just to be clear, I am using
setTitle:forState
in the example above. -
user593301 over 10 yearsFYI: UITextAlignmentCenter is deprecated in iOS 6 and NSTextAlignmentCenter should now be used instead.
-
dchakarov over 7 yearsIn Swift
button.titleLabel?.textAlignment = .Left
worked for me. -
bubbaspike over 2 yearsTextAlignment
.leading
has been introduced since then. This might better fit your multiline text. I noticed similar issue with.right
vs..trailing
textAlignments and found .trailing to be better. Also noticed .trailing worked with RTL languages too.