85

How do you center the text inside a UILabel?

Chris
  • 1,343
  • 3
  • 11
  • 18

9 Answers9

204

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
Community
  • 1
  • 1
Henrik P. Hessel
  • 36,243
  • 17
  • 80
  • 100
27

This is depreciated now in iOS6.

You should use:

yourLabel.textAlignment = NSTextAlignmentCenter;
R2D2
  • 2,620
  • 4
  • 24
  • 46
6

Besides using code, as Henrik suggested, you can also set the appropriate property in Interface Builder.

Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
1

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
apinho
  • 2,235
  • 3
  • 25
  • 39
0

UITextAlignmentCenter is deprecated since NSTextAlignmentCenter since iOS 6.0. You should use NSTextAlignmentCenter instead:

[label setTextAlignment:NSTextAlignmentCenter];
Luciano Rodríguez
  • 2,239
  • 3
  • 19
  • 32
0

As of Xcode 10.2.1 use:

UIlabel.textAlignment = NSTextAlignment.center
M Waz
  • 755
  • 1
  • 7
  • 18
0

Try this code:

labelName.textAlignment = UITextAlignmentCenter
Aitul
  • 2,982
  • 2
  • 24
  • 52
Ayush Goel
  • 1,103
  • 1
  • 7
  • 7
0

Using UIBUILDER (Swift 4) (EZ!)

Center UILabel text most easily using the "Alignment" property inside the label's Attributes Inspector. (fig. 1)

"Figure 1"

John Pitts
  • 653
  • 6
  • 17
0

Try out the following code:

lblObject.textAlignment=UITextAlignmentCenter;

Hope this helps you.

kender
  • 85,663
  • 26
  • 103
  • 145
Ankit Gupta
  • 958
  • 1
  • 6
  • 19