Reputation: 467
I want to set the alignment of a text label, how can I do that?
Upvotes: 27
Views: 38760
Reputation: 3082
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
Upvotes: 48
Reputation: 722
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
Upvotes: 2
Reputation: 1897
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
}
Upvotes: 27
Reputation: 396
In Swift 3 and beyond it should be
yourlabel.textAlignment = NSTextAlignment.center
Upvotes: 2
Reputation: 2285
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
Upvotes: 2
Reputation: 22726
Here you are,
yourLabel.textAlignment = UITextAlignmentCenter
EDIT
if you target above iOS6 use NSTextAlignmentCenter
as UITextAlignmentCenter
is depreciated
Hope it helps.
Upvotes: 28