如何通过Swift语言编程创buildUILabel?

如何在Xcode 6中使用Swift语言以编程方式创buildUILabel

我已经开始在Xcode 6中使用一个新的“单一视图应用程序”,并为这个项目selectSwift语言。 我有我的文件AppDelegate.swiftViewController.swift ,我不知道从这里做什么。

 override func viewDidLoad() { super.viewDidLoad() var label = UILabel(frame: CGRectMake(0, 0, 200, 21)) label.center = CGPointMake(160, 284) label.textAlignment = NSTextAlignment.Center label.text = "I'am a test label" self.view.addSubview(label) } 

Swift 3.0更新:

 let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21)) label.center = CGPoint(x: 160, y: 285) label.textAlignment = .center label.text = "I'am a test label" self.view.addSubview(label) 

以下是Swift 3的正确代码,并附有说明用途的注释:

 override func viewDidLoad() { super.viewDidLoad() // CGRectMake has been deprecated - and should be let, not var let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21)) // you will probably want to set the font (remember to use Dynamic Type!) label.font = UIFont.preferredFont(forTextStyle: .footnote) // and set the text color too - remember good contrast label.textColor = .black // may not be necessary (eg, if the width & height match the superview) // if you do need to center, CGPointMake has been deprecated, so use this label.center = CGPoint(x: 160, y: 284) // this changed in Swift 3 (much better, no?) label.textAlignment = .center label.text = "I am a test label" self.view.addSubview(label) } 

为了添加已经很好的答案,你可能需要在你的项目中添加多个标签,这样做(设置大小,样式等)将是一个痛苦。 为了解决这个问题,你可以创build一个单独的UILabel类。

  import UIKit class MyLabel: UILabel { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initializeLabel() } override init(frame: CGRect) { super.init(frame: frame) initializeLabel() } func initializeLabel() { self.textAlignment = .left self.font = UIFont(name: "Halvetica", size: 17) self.textColor = UIColor.white } } 

要使用它,请执行以下操作

 import UIKit class ViewController: UIViewController { var myLabel: MyLabel() override func viewDidLoad() { super.viewDidLoad() myLabel = MyLabel(frame: CGRect(x: self.view.frame.size.width / 2, y: self.view.frame.size.height / 2, width: 100, height: 20)) self.view.addSubView(myLabel) } } 

您可以使用下面的代码创build标签。

 var yourLabel: UILabel = UILabel() yourLabel.frame = CGRectMake(50, 150, 200, 21) yourLabel.backgroundColor = UIColor.orangeColor() yourLabel.textColor = UIColor.blackColor() yourLabel.textAlignment = NSTextAlignment.Center yourLabel.text = "test label" self.view.addSubview(yourLabel)