How do you center the text inside a UILabel?
One way to center text or put it in the middle of the page is to enclose it within <center></center> tags. Inserting this text within HTML code would yield the following result: Center this text!
You can also change the label text alignment by change the UILabel object's textAlignment property value t0 NSTextAlignment. left , NSTextAlignment. center or NSTextAlignment. right .
Use NSTextAlignmentCenter if what you have is the label already set and you want to center its content. This is the best answer, having the label frame is centered is not enough for centering the text, very useful if your labels are localized!
The Code is
[yourLabel setTextAlignment:UITextAlignmentCenter];
or (of course) the Obj-C 2.0 Dot-Syntax
yourLabel.textAlignment = UITextAlignmentCenter;
For iOS 6 (and higher) you should use NSTextAlignmentCenter
instead of UITextAlignmentCenter
:
yourLabel.textAlignment = NSTextAlignmentCenter;
Source
And if you want backward compatibiliy to iOS 5 also you can do this,
#ifdef __IPHONE_6_0 # define ALIGN_CENTER NSTextAlignmentCenter #else # define ALIGN_CENTER UITextAlignmentCenter #endif
Swift 3
yourLabel.textAlignment = .center
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