我想设置文本标签的对齐方式,我该怎么做?
答案 0 :(得分:45)
我认为有答案帮助了你。正确的方法是:
yourLabelName.textAlignment = NSTextAlignmentCenter;
有关更多文档,您可以阅读: https://developer.apple.com/documentation/uikit/uilabel
在斯威夫特: -
yourLabelName.textAlignment = .center
此处.center
为NSTextAlignment.center
答案 1 :(得分:28)
你在这里,
yourLabel.textAlignment = UITextAlignmentCenter
修改强>
如果您定位在iOS6以上,请使用NSTextAlignmentCenter
,因为UITextAlignmentCenter
已弃用
希望它有所帮助。
答案 2 :(得分:27)
从iOS 6.0开始,这已发生变化UITextAlignment has been deprecated。现在正确的做法是:
yourLabel.textAlignment = NSTextAlignmentCenter;
这是可枚举的NSTextAlignment,它提供了文本对齐的选项:
目标-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
}
答案 3 :(得分:9)
label.textAlignment = NSTextAlignmentCenter;
答案 4 :(得分:2)
如果您有多行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
答案 5 :(得分:2)
在Swift 3及更高版本中它应该是
yourlabel.textAlignment = NSTextAlignment.center
答案 6 :(得分:2)
快速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
答案 7 :(得分:-2)
Yourlabel.textAlignment = UITextAlignmentCenter;