将标签代码从 playground 移至故事板

Moving label code from playgrounds to storyboard

我在没有编程经验的情况下开始探索 Swift2。

我有以下代码在 Playgrounds 中使用快速查看和内联查看方法效果很好。

如何将它与故事板中的实际标签相关联?

import UIKit

let myLabel = UILabel(frame: CGRectMake(0, 0, 200, 50))
myLabel.backgroundColor = UIColor.redColor()  
myLabel.text = "Hello Swift"  
myLabel.textAlignment = .Center   
myLabel.font = UIFont(name: "Georgia", size: 24)

摘自:史密斯,尼尔。 “iOS 9 个应用程序开发要点。”有效载荷媒体,0101-01-01T00:00:00+00:00。电子书。 此 material 可能受版权保护。

您可以在 viewController 中的 viewDidLoad() 方法中使用您的代码。接下来,您可能希望将标签添加到主视图中。

一个例子:

override func viewDidLoad() {
    super.viewDidLoad()

    let myLabel = UILabel(frame: CGRectMake(0, 0, 200, 50))
    myLabel.backgroundColor = UIColor.redColor()
    myLabel.text = "Hello Swift"
    myLabel.textAlignment = .Center
    myLabel.font = UIFont(name: "Georgia", size: 24)
    self.view.addSubview(myLabel)
}

要将标签添加到您的视图中: 转到您的 ViewController.swift 文件,并添加以下代码:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    //Add the code for your label here
    self.view.addSubview(myLabel)
}