2015-06-17 55 views
0

我在故事板中有2個視圖。第一個視圖是一個登錄屏幕,用戶輸入電子郵件和密碼,點擊登錄按鈕後,函數創建一個與API的HTTP連接,API檢查並認證用戶併發回JSON數據。如何使用編程方式執行Segue時的PrepareForSegue

dispatch_async(dispatch_get_main_queue()) { 

      let storyboard = UIStoryboard(name: "Main", bundle: nil) 
      let vc = storyboard.instantiateViewControllerWithIdentifier("detailView") as! UIViewController 
      self.presentViewController(vc, animated: true, completion: nil) 
       } 

如何從VIEW 1 JSON數據傳遞到VIEW 2:現在的JSON數據是鑑於1.如下面的代碼所示我已經編程執行我的SEGUE?我試圖使用prepareForSegue由於要求的segue標識符,因爲我有編程執行我的segue我沒有segue標識符。我的故事板圖像低於:

enter image description here

任何幫助將不勝感激。 在此先感謝。如果您需要更多信息來回答問題,請讓我知道。

回答

1

,而不是這個,你可以在你的新類中設置的功能和數據推送到這樣的:

dispatch_async(dispatch_get_main_queue()) { 
      let storyboard = UIStoryboard(name: "Main", bundle: nil) 
      let vc = storyboard.instantiateViewControllerWithIdentifier("detailView") as! UIViewController 
      vc.setJSONObject(yourJSON) 
      self.presentViewController(vc, animated: true, completion: nil) 
} 

在UIViewController您可以定義一個函數調用setJSONObject

func setJSONObject(json:AnyObject){ 
    print(json) 
} 
+0

謝謝你的回覆一個例子。我嘗試了上面的代碼,但是我以編程方式調用segue的類沒有識別出「setJSONObject」,它出現了一個錯誤,提示「UIViewController沒有名爲setJSONObject的成員」。我也在第二個視圖中創建了該功能。 – Skywalker

+0

請注意,您可以並應該使用'prepareForSegue'方法。 'presentViewController'增加了新的ViewController ** modally **,根據你對問題的描述,這不是你想要的東西。這裏是官方的Apple文檔https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/#//apple_ref/occ/instm/UIViewController/presentViewController:animated:completion: –

1

使用標識符在Interface Builder中創建一個segue。

使用下面的代碼來執行SEGUE:

self.performSegueWithIdentifier("MySegue", sender: self); 

這樣prepareForSegue將被執行。

這裏是什麼可能看起來像你的情況

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 

    if (segue.identifier == "MySegue") 
    { 
     if let detailsViewController = segue.destinationViewController as? DetailViewController { 
      detailsViewController.jsonData = YOUR_JSON_STUFF; 
     } 

    } 
} 
+0

謝謝你的回覆。我會在哪裏放置這段代碼?與我的代碼,我正在執行segue編程? – Skywalker

+0

不,您應該使用此行替換您創建的代碼。 (最好在Swift中)這會自動實例化你的第二個視圖控制器並對它執行segue。接下來,您可以在'prepareForSegue'中獲得對'destinationViewController'的引用,您可以在其中設置屬性。 –

+0

在這裏你可以找到'prepareForSegue'中的代碼可能看起來像一個例子http://stackoverflow.com/questions/7864371/how-to-pass-prepareforsegue-an-object –