Ios – How to create UILabel programmatically using Swift

cocoa-touchiosswiftuilabelxcode

How do I create a UILabel programmatically using Swift in Xcode 6?

I have started with a new "Single View Application" in Xcode 6 and selected Swift for this project. I have my files AppDelegate.swift and ViewController.swift and I'm not sure what to do from here.

Best Answer

Creating a UILabel programmatically in Swift 3+:

override func viewDidLoad() {
    super.viewDidLoad()

    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'm a test label"

    self.view.addSubview(label)
}