在UILabel中居中显示文字


Answers:


198

该守则是

[yourLabel setTextAlignment:UITextAlignmentCenter];

或(当然)Obj-C 2.0点语法

yourLabel.textAlignment = UITextAlignmentCenter;

对于iOS 6(及更高版本),您应该使用NSTextAlignmentCenter而不是UITextAlignmentCenter

yourLabel.textAlignment = NSTextAlignmentCenter;

资源

如果您想向后兼容iOS 5,也可以这样做,

#ifdef __IPHONE_6_0
# define ALIGN_CENTER NSTextAlignmentCenter
#else
# define ALIGN_CENTER UITextAlignmentCenter
#endif

迅捷3

yourLabel.textAlignment = .center

2
或少一些括号:yourLabel.textAlignment = UITextAlignmentCenter;
Peter DeWeese

11
iOS 6.0之后不推荐使用UITextAlignmentCenter。现在使用NSTextAlignmentCenter。
Dev2rights 2013年

3
还要注意,如果在设置textAlignment之后调用[yourLabel sizeToFit],它将以左对齐结尾并忽略textAlignment属性。
DiscDev 2013年

26

现在在iOS6中已贬值。

您应该使用:

yourLabel.textAlignment = NSTextAlignmentCenter;


1

如果您有多行UILabel,则应使用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




0

从Xcode 10.2.1开始,使用:

UIlabel.textAlignment = NSTextAlignment.center
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.