27

I want to set the alignment of a text label, how can I do that?

8 Answers 8

48

I think there are the answers who helped you out. The correct way to do this is:

yourLabelName.textAlignment = NSTextAlignmentCenter;

for more documentation you can read this: https://developer.apple.com/documentation/uikit/uilabel

In Swift :-

yourLabelName.textAlignment = .center

Here .center is NSTextAlignment.center

3
28

Here you are,

yourLabel.textAlignment = UITextAlignmentCenter

EDIT

if you target above iOS6 use NSTextAlignmentCenter as UITextAlignmentCenter is depreciated

Hope it helps.

27

This has changed as of iOS 6.0, UITextAlignment has been deprecated. The correct way to do this now is:

yourLabel.textAlignment = NSTextAlignmentCenter;

Here is the NSTextAlignment enumerable that gives the options for text alignment:

Objective-C:

enum {
   NSTextAlignmentLeft      = 0,
   NSTextAlignmentCenter    = 1,
   NSTextAlignmentRight     = 2,
   NSTextAlignmentJustified = 3,
   NSTextAlignmentNatural   = 4,
};
typedef NSInteger NSTextAlignment;

Swift:

enum NSTextAlignment : Int {
    case Left
    case Center
    case Right
    case Justified
    case Natural
}

Source

1
  • @nari please accept this answer. Is the most up to date
    – mm24
    Jan 28, 2015 at 11:47
9
label.textAlignment = NSTextAlignmentCenter;

see UILabel documentation

0
2

If you have a multiline UILabel you should use a NSMutableParagraphStyle

   yourLabelName.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)
   yourLabelName.attributedText = attributedText
2

In Swift 3 and beyond it should be

yourlabel.textAlignment = NSTextAlignment.center
2

in swift 4:

 let paragraphStyle = NSMutableParagraphStyle()
 paragraphStyle.alignment = NSTextAlignment.center

 // in Swift 4.2
 let attributedString = NSMutableAttributedString(string: "Your String", attributes:[NSAttributedString.Key.paragraphStyle:paragraphStyle])

 // in Swift 4.1--
 let attributedString = NSMutableAttributedString(string: "Your String", attributes: [NSAttributedStringKey.paragraphStyle:paragraphStyle])

 let yourLabel = UILabel()
 yourLabel.attributedText = attributedString
-2
Yourlabel.textAlignment = UITextAlignmentCenter;
1
  • UITextAlignmentCenter is deprecated. Use NSTextAlignmentCenter as suggested below instead. Jan 12, 2014 at 1:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.