介紹一下如何用 Segue 傳值, 當然也是 Swift 版本的

  1. 首先在 Storyboard 新增一個 ViewController

    First add new viewController into your storyboard.

  2. 選擇 Root View Controllerview controller icon 按住ctrl 然後把線拖放到 新的ViewController

    Choose view controller icon on the top of root view controller, then press ctrl drag the line to new view controller to add new segue.

  3. 先選 Show 就好

  4. 新增一個 Swift file : ReceiveSegueDataViewController(名稱可自取)

    Add new swift file : ReceiveSegueDataViewController(Name can change by yourself)

    import Foundation
    class HotPlaceMainViewController : UIViewController {    
    var receiveData: String!
    override func viewDidLoad() {
        super.viewDidLoad();
        println(receiveData);
    }    
    }
    
  5. 在Storyboard中, 設定新的View Controller 的 class 為 HotPlaceMainViewController

    Set HotPlaceMainViewController as new view controller for New controller View in StoryBoard.

  6. 設定 Segue 的 identifier 為 sendData 如下圖, 用來辨識是哪一個 Segue 要傳什麼值過去

    Set the identifier "sendData" to the segue. You can refer the below image , that is used to identify which segue we used to pass value.

  7. 回到 Root View Controller 新增 Override 的 function : prepareForSegue

    Let's add new override function "prepareForSegue" to handle view change by segue.

    override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if segue.identifier == "sendData" {
          //get destination controller
        var destViewController = segue.destinationViewController as HotPlaceMainViewController;
        destViewController.receiveData = "SegueData!!!!!";
    }
    }
    
  8. 完成. 這樣在 View 準備換場時就會呼叫 prepareForSegue 在裡面可以得到 destination View controller 的 Object 然後把值放進去 達成傳值的動作

    Complete! So before root view change to next view that will call prepareForSegue to help you set the data to destination view object's variable to comeplete the action.

P.S. 傳值不可以指定下一個View 裡的 UI Object, 不然會有找不到的問題
You can't set value to UI object in destination view or you will get nil pointer error in runtime.