我如何在UILabel对齐文本?


当前回答

对于Swift 3,它是:

label.textAlignment = .center

其他回答

使用yourLabel。textAlignment = NSTextAlignmentCenter;为iOS >= 6.0和yourLabel。textAlignment = UITextAlignmentCenter;适用于iOS < 6.0。

IO6.1 [lblTitle setTextAlignment NSTextAlignmentCenter):;

注意:根据UILabel类引用,从iOS 6开始,这种方法现在已弃用。

只需使用textAlignment属性来查看使用UITextAlignment值之一所需的对齐。(UITextAlignmentLeft, UITextAlignmentCenter或UITextAlignmentRight。)

例如:[myUILabel setTextAlignment:UITextAlignmentCenter];

更多信息请参见UILabel类参考。

Label.textAlignment = NSTextAlignmentCenter;

在Swift 4.2和Xcode 10中

let lbl = UILabel(frame: CGRect(x: 10, y: 50, width: 230, height: 21))
lbl.textAlignment = .center //For center alignment
lbl.text = "This is my label fdsjhfg sjdg dfgdfgdfjgdjfhg jdfjgdfgdf end..."
lbl.textColor = .white
lbl.backgroundColor = .lightGray//If required
lbl.font = UIFont.systemFont(ofSize: 17)

 //To display multiple lines in label
lbl.numberOfLines = 0
lbl.lineBreakMode = .byWordWrapping

lbl.sizeToFit()//If required
yourView.addSubview(lbl)