How do you programmatically center the alignment of a text label for iOS?

37,715

Solution 1

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

Solution 2

Here you are,

yourLabel.textAlignment = UITextAlignmentCenter

EDIT

if you target above iOS6 use NSTextAlignmentCenter as UITextAlignmentCenter is depreciated

Hope it helps.

Solution 3

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

Solution 4

label.textAlignment = NSTextAlignmentCenter;

see UILabel documentation

Solution 5

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
Share:
37,715

Related videos on Youtube

nari
Author by

nari

Updated on July 09, 2022

Comments

  • nari
    nari almost 2 years

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

  • Nick Merrill
    Nick Merrill over 10 years
    UITextAlignmentCenter is deprecated. Use NSTextAlignmentCenter as suggested below instead.