如何在 UILabel 中将文本居中?
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:
NSTextAlignmentCenter
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
Besides using code, as Henrik suggested, you can also set the appropriate property in Interface Builder.
Try this code:
labelName.textAlignment = UITextAlignmentCenter
Try out the following code:
lblObject.textAlignment=UITextAlignmentCenter;
Hope this helps you.
This is depreciated now in iOS6.
You should use:
UITextAlignmentCenter is deprecated since NSTextAlignmentCenter since iOS 6.0. You should use NSTextAlignmentCenter instead:
[label setTextAlignment:NSTextAlignmentCenter];
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
As of Xcode 10.2.1 use:
UIlabel.textAlignment = NSTextAlignment.center
Using UIBUILDER (Swift 4) (EZ!)
Center UILabel text most easily using the "Alignment" property inside the label's Attributes Inspector. (fig. 1)