UILabel对齐文本到中心

我如何在UILabel对齐文本?

208777 次浏览

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

只需使用textAlignment属性就可以使用其中一个UITextAlignment值查看所需的对齐方式。(UITextAlignmentLeftUITextAlignmentCenterUITextAlignmentRight。)

例如:[myUILabel setTextAlignment:UITextAlignmentCenter];

更多信息请参见UILabel类引用

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

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

你可以阅读更多关于它在这里UILabel

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

myLabel.textAlignment = NSTextAlignmentCenter;

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

myLabel.textAlignment = .center
< p > IO6.1 [lblTitle setTextAlignment:NSTextAlignmentCenter]; < / p >

使用yourLabel.textAlignment = NSTextAlignmentCenter; for iOS >= 6.0和yourLabel.textAlignment = UITextAlignmentCenter; for iOS <6.0.

Label.textAlignment = NSTextAlignmentCenter;

要在Swift的UILabel中居中文本(这是针对iOS 7+),你可以做:

myUILabel.textAlignment = .Center

myUILabel.textAlignment = NSTextAlignment.Center

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

title.TextAlignment = UITextAlignment.Center;

对于Swift 3,它是:

label.textAlignment = .center

斯威夫特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)