How do you center the text inside a UILabel?
9 Answers
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;
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

- 1
- 1

- 36,243
- 17
- 80
- 100
-
2Or with a little less bracket soup: yourLabel.textAlignment = UITextAlignmentCenter; – Peter DeWeese Jun 15 '11 at 19:58
-
12UITextAlignmentCenter is deprecated after iOS 6.0. Now use NSTextAlignmentCenter. – Dev2rights Mar 01 '13 at 15:12
-
3Also note that if you call [yourLabel sizeToFit] after setting the textAlignment, it will end up left-justified and ignore the textAlignment property. – DiscDev May 07 '13 at 15:35
This is depreciated now in iOS6.
You should use:
yourLabel.textAlignment = NSTextAlignmentCenter;

- 2,620
- 4
- 24
- 46
Besides using code, as Henrik suggested, you can also set the appropriate property in Interface Builder.

- 176,835
- 32
- 241
- 292
-
How? Content Mode doesn't work. Niether does Alignment. So what in Interface Builder does it? – John Pitts Aug 19 '21 at 16:57
If you have a multiline UILabel you should use a NSMutableParagraphStyle
label.numberOfLines = 0
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .Center
let attributes : [String : AnyObject] = [NSFontAttributeName : UIFont(name: "HelveticaNeue", size: 15)!, NSParagraphStyleAttributeName: paragraphStyle]
let attributedText = NSAttributedString.init(string: subTitleText, attributes: attributes)
label.attributedText = attributedText

- 2,235
- 3
- 25
- 39
UITextAlignmentCenter is deprecated since NSTextAlignmentCenter since iOS 6.0. You should use NSTextAlignmentCenter instead:
[label setTextAlignment:NSTextAlignmentCenter];

- 2,239
- 3
- 19
- 32
Try this code:
labelName.textAlignment = UITextAlignmentCenter

- 2,982
- 2
- 24
- 52

- 1,103
- 1
- 7
- 7
Using UIBUILDER (Swift 4) (EZ!)
Center UILabel text most easily using the "Alignment" property inside the label's Attributes Inspector. (fig. 1)

- 653
- 6
- 17
Try out the following code:
lblObject.textAlignment=UITextAlignmentCenter;
Hope this helps you.

- 85,663
- 26
- 103
- 145

- 958
- 1
- 6
- 19