我如何在UILabel对齐文本?


当前回答

在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)

其他回答

下面是一个示例代码,展示如何使用UILabel对齐文本:

label = [[UILabel alloc] initWithFrame:CGRectMake(60, 30, 200, 12)];
label.textAlignment = NSTextAlignmentCenter;

你可以在这里UILabel阅读更多

在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)
Label.textAlignment = NSTextAlignmentCenter;

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

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

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

例如:[myUILabel setTextAlignment:UITextAlignmentCenter];

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