Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel Align Text to center

From iOS 6 and later UITextAlignment is deprecated. use NSTextAlignment

myLabel.textAlignment = NSTextAlignmentCenter;

Swift Version from iOS 6 and later

myLabel.textAlignment = .center

Here is a sample code showing how to align text using UILabel:

label = [[UILabel alloc] initWithFrame:CGRectMake(60, 30, 200, 12)];
label.textAlignment = NSTextAlignmentCenter;

You can read more about it here UILabel


To center text in a UILabel in Swift (which is targeted for iOS 7+) you can do:

myUILabel.textAlignment = .Center

Or

myUILabel.textAlignment = NSTextAlignment.Center

N.B.: As per the UILabel class reference, as of iOS 6 this approach is now deprecated.

Simply use the textAlignment property to see the required alignment using one of the UITextAlignment values. (UITextAlignmentLeft, UITextAlignmentCenter or UITextAlignmentRight.)

e.g.: [myUILabel setTextAlignment:UITextAlignmentCenter];

See the UILabel Class Reference for more information.


Use yourLabel.textAlignment = NSTextAlignmentCenter; for iOS >= 6.0 and yourLabel.textAlignment = UITextAlignmentCenter; for iOS < 6.0.


For Swift 3 it's:

label.textAlignment = .center