This will make exactly what you were expecting:
Objective-C:
[myButton.titleLabel setTextAlignment:UITextAlignmentCenter];
For iOS 6 or higher it's
[myButton.titleLabel setTextAlignment: NSTextAlignmentCenter];
as explained in tyler53's answer
Swift:
myButton.titleLabel?.textAlignment = NSTextAlignment.Center
Swift 4.x and above
myButton.titleLabel?.textAlignment = .center
Use the line:
myButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
This should center the content (horizontally).
And if you want to set the text inside the label to the center as well, use:
[labelOne setTextAlignment:UITextAlignmentCenter];
If you want to use IB, I've got a small example here which is linked in XCode 4 but should provide enough detail (also mind, on top of that properties screen it shows the property tab. You can find the same tabs in XCode 3.x):
You can set the key path in the storyboard
Set the text to your multiline title e.g. hello
⌥ + ↵ multiline
You need to press ⌥ + ↵ to move text to next line.
Then add the key path
titleLabel.textAlignment
as Number
and value 1
, 1
means NSTextAlignmentCenter
titleLabel.numberOfLines
as Number
and value 0
, 0
means any number of lines
This will not be reflected on IB/Xcode, but will be in centre at run time (device/simulator)
If you want to see the changes on Xcode you need to do the following: (remember you can skip these steps)
Subclass the UIButton to make the button designable:
import UIKit
@IBDesignable class UIDesignableButton: UIButton {}
Assign this designable subclass to the buttons you're modifying:
If you want to write the code, then do the long process
1.Create IBOutlet
for button
2.Write code in viewDidLoad
btn.titleLabel.textAlignment = .Center
btn.titleLabel.numberOfLines = 0
In newer version of xcode (mine is xcode 6.1) we have property attributed title
Select Attributed
then select the text and press centre option below
P.S. The text was not coming multiline for that I have to set the
btn.titleLabel.numberOfLines = 0
For UIButton you should use:-
[btn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
For ios 8 and Swift
btn.titleLabel.textAlignment = NSTextAlignment.Center
or
btn.titleLabel.textAlignment = .Center
For those of you who are now using iOS 6 or higher, UITextAlignmentCenter has been deprecated. It is now NSTextAlignmentCenter
EXAMPLE: mylabel.textAlignment = NSTextAlignmentCenter;
Works perfectly.
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