我如何在UILabel对齐文本?


当前回答

Label.textAlignment = NSTextAlignmentCenter;

其他回答

IO6.1 [lblTitle setTextAlignment NSTextAlignmentCenter):;

在xamarin ios 假设您的标签名称是title,然后执行以下操作

title.TextAlignment = UITextAlignment.Center;

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

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

例如:[myUILabel setTextAlignment:UITextAlignmentCenter];

更多信息请参见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)

从iOS 6及以后,UITextAlignment已弃用。使用NSTextAlignment

myLabel.textAlignment = NSTextAlignmentCenter;

Swift版本来自iOS 6及更高版本

myLabel.textAlignment = .center