UILabel将文本居中对齐


Answers:


568

iOS 6及更高版本开始UITextAlignment不推荐使用。用NSTextAlignment

myLabel.textAlignment = NSTextAlignmentCenter;

iOS 6及更高版本的Swift版本

myLabel.textAlignment = .center

8
快速版本可以简化:) myLabel.textAlignment = .Center
aryaxt 2015年

1
.center←小写字母
Lucas

83

以下示例代码显示了如何使用UILabel对齐文本:

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

您可以在此处了解更多有关UILabel的信息


27
UITextAlignment自iOS 5起不推荐使用NSTextAlignment。改为使用。
Philip007

False,不推荐使用UITextAligment。在UIStringDrawing.h(UIKit)中,您可以找到以下代码:// Deprecated: use NSTextAlignment enum in UIKit/NSText.h typedef NS_ENUM(NSInteger, UITextAlignment) { UITextAlignmentLeft = 0, UITextAlignmentCenter, UITextAlignmentRight, // could add justified in future } NS_DEPRECATED_IOS(2_0,6_0);
aramusss 2015年

12

要在Swift(针对iOS 7+)中将UILabel中的文本居中,您可以执行以下操作:

myUILabel.textAlignment = .Center

要么

myUILabel.textAlignment = NSTextAlignment.Center

8

注意:根据UILabel类参考,自iOS 6起,此方法现已弃用。

只需使用textAlignment属性使用UITextAlignment值之一查看所需的对齐方式。(UITextAlignmentLeftUITextAlignmentCenterUITextAlignmentRight)。

例如: [myUILabel setTextAlignment:UITextAlignmentCenter];

有关更多信息,请参见UILabel类参考


6

使用yourLabel.textAlignment = NSTextAlignmentCenter;针对iOS> = 6.0和yourLabel.textAlignment = UITextAlignmentCenter;为iOS <6.0。






0

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)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.