如何以编程方式将iOS文本标签alignment?

我想设置文本标签的alignment方式,我该怎么做?

我认为有帮助你的答案。 正确的方法是:

yourLabelName.textAlignment = NSTextAlignmentCenter; 

更多的文档可以阅读: https : //developer.apple.com/documentation/uikit/uilabel

这个给你,

 yourLabel.textAlignment = UITextAlignmentCenter 

编辑

如果您定位到iOS6以上,则使用NSTextAlignmentCenter因为UITextAlignmentCenter已折旧

希望能帮助到你。

这已经改变为iOS 6.0, UITextAlignment已被弃用 。 现在正确的做法是:

 yourLabel.textAlignment = NSTextAlignmentCenter; 

这里是NSTextAlignment枚举,给出了文本alignment的选项:

Objective-C的:

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

迅速:

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

资源

 label.textAlignment = NSTextAlignmentCenter; 

请参阅UILabel文档

如果你有一个多行UILabel你应该使用一个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 

在Swift 3以后,应该是

 yourlabel.textAlignment = NSTextAlignment.center 
 Yourlabel.textAlignment = UITextAlignmentCenter;