UILabel Align Text to center
Solution 1
From iOS 6 and later UITextAlignment
is deprecated. use NSTextAlignment
myLabel.textAlignment = NSTextAlignmentCenter;
Swift Version from iOS 6 and later
myLabel.textAlignment = .center
Solution 2
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
Solution 3
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
Solution 4
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.
Solution 5
Use yourLabel.textAlignment = NSTextAlignmentCenter;
for iOS >= 6.0 and yourLabel.textAlignment = UITextAlignmentCenter;
for iOS < 6.0.
Related videos on Youtube
vivianaranha
Updated on November 09, 2021Comments
-
vivianaranha over 2 years
How do I align text in
UILabel
? -
Philip007 over 11 years
UITextAlignment
is deprecated since iOS 5. UseNSTextAlignment
instead. -
aryaxt about 9 yearsswift version could be simplified :) myLabel.textAlignment = .Center
-
aramusss about 9 yearsFalse, UITextAligment is deprecated. In UIStringDrawing.h (UIKit) you can find this code:
// Deprecated: use NSTextAlignment enum in UIKit/NSText.h typedef NS_ENUM(NSInteger, UITextAlignment) { UITextAlignmentLeft = 0, UITextAlignmentCenter, UITextAlignmentRight, // could add justified in future } NS_DEPRECATED_IOS(2_0,6_0);
-
FelixSFD over 7 yearsThe question is not about Xamarin. And
UITextAlignment
is deprecated in iOS 6! -
Lucas about 7 years.center ← lowercase