第一次用 Swift 寫一個很簡單的 iPhone App

之前蘋果推出了新的編程話言 Swift,我未學過 Objective C,但就嘗試性用 Swift 在 ViewController 上試寫最簡單的 iPhone App,未用上 Story Board。

由於新的 Xcode 6 仍在 Beta 階段,所以要先登記為 iOS 的開發者才可下載 Beta 的 Xcode。

就是這樣開了一個新的 Single View Application,再於 ViewController.swift 上寫以下程式:
import UIKit

class ViewController: UIViewController, UIAlertViewDelegate   {
                            
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.    
        var button = UIButton.buttonWithType(UIButtonType.System) as UIButton
        button.frame.origin = CGPointMake(100.0, 150.0)
        button.frame.size = CGSizeMake(150,50)
        button.setTitle("Click me!", forState: UIControlState.Normal)
        button.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(button)
        println("here!")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func buttonClick(sender: UIButton!){
        let alert = UIAlertView()
        alert.title = "alert"
        alert.delegate = self
        alert.addButtonWithTitle("Yeah!")
        alert.message = "Hello World"
        alert.show()
    }
}

用 simulator 執行會有一個按鈕,按下會有一個 Alert Box 彈出來:
Screen Shot 2014-06-24 at 10.08.21 pm

在自己的 iPhone 上執行:
IMG_6454

按下按鈕:
IMG_6455

參考連結:
Swift UI开发初探
Hello World! App

本文連結