Center text in a UILabel

IphoneObjective C

Iphone Problem Overview


How do you center the text inside a UILabel?

Iphone Solutions


Solution 1 - Iphone

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

Solution 2 - Iphone

This is depreciated now in iOS6.

You should use:

yourLabel.textAlignment = NSTextAlignmentCenter;

Solution 3 - Iphone

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

Solution 4 - Iphone

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

Solution 5 - Iphone

Try this code:

labelName.textAlignment = UITextAlignmentCenter

Solution 6 - Iphone

Try out the following code:

lblObject.textAlignment=UITextAlignmentCenter;

Hope this helps you.

Solution 7 - Iphone

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

[label setTextAlignment:NSTextAlignmentCenter];

Solution 8 - Iphone

As of Xcode 10.2.1 use:

UIlabel.textAlignment = NSTextAlignment.center

Solution 9 - Iphone

Using UIBUILDER (Swift 4) (EZ!)

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChrisView Question on Stackoverflow
Solution 1 - IphoneHenrik P. HesselView Answer on Stackoverflow
Solution 2 - IphoneR2D2View Answer on Stackoverflow
Solution 3 - IphonePablo Santa CruzView Answer on Stackoverflow
Solution 4 - IphoneapinhoView Answer on Stackoverflow
Solution 5 - IphoneAyush GoelView Answer on Stackoverflow
Solution 6 - IphoneAnkit GuptaView Answer on Stackoverflow
Solution 7 - IphoneLuciano RodríguezView Answer on Stackoverflow
Solution 8 - IphoneM WazView Answer on Stackoverflow
Solution 9 - IphoneJohn PittsView Answer on Stackoverflow