Answers:
以下示例代码显示了如何使用UILabel对齐文本:
label = [[UILabel alloc] initWithFrame:CGRectMake(60, 30, 200, 12)];
label.textAlignment = NSTextAlignmentCenter;
您可以在此处了解更多有关UILabel的信息
UITextAlignment
自iOS 5起不推荐使用NSTextAlignment
。改为使用。
// 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);
注意:根据UILabel类参考,自iOS 6起,此方法现已弃用。
只需使用textAlignment
属性使用UITextAlignment
值之一查看所需的对齐方式。(UITextAlignmentLeft
,UITextAlignmentCenter
或UITextAlignmentRight
)。
例如: [myUILabel setTextAlignment:UITextAlignmentCenter];
有关更多信息,请参见UILabel类参考。
使用yourLabel.textAlignment = NSTextAlignmentCenter;
针对iOS> = 6.0和yourLabel.textAlignment = UITextAlignmentCenter;
为iOS <6.0。
对于Swift 3,它是:
label.textAlignment = .center
在xamarin ios中,假设您的标签名称为title,然后执行以下操作
title.TextAlignment = UITextAlignment.Center;
UITextAlignment
被弃用iOS 6中!
在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)