2017-10-04 69 views
0

我試圖將數據傳遞給第二視圖控制器沒有成功,
這是我的代碼:

如何以編程方式導航到視圖控制器,並通過數據

let storyboard = UIStoryboard(name: "Main", bundle: nil) 
let vc = storyboard.instantiateViewController(withIdentifier: 「secondVC") 
self.present(vc, animated: true, completion: nil) 

//The following solution as I checked in the previous questions doesn't work: 

vc.Var1InSecondViewController = self.var1 
vc.Var2InSecondViewController = self.var2 


它聲稱「與第二個視圖控制器相關的「vc」沒有'Var1InSecondViewController'的成員,儘管我在第二個視圖控制器中創建了它。

您的幫助將不勝感激,謝謝。

+0

添加代碼的第二個視圖控制器,具有vc.Var1InSecondViewController – Krunal

+0

@Krunal的減速我在疑問,我已經做到了提及:「即使我沒有在創建它第二個視圖控制器「 – Yossi

+0

此問題的答案需要第二個視圖控制器的類名稱和第二個視圖控制器中的變量的參數訪問級別。看看Bharath的答案,這可能是正確的,但只有視圖控制器類名缺失。 – Krunal

回答

2

你必須爲以如下方式訪問其屬性來指定secondVC的類名,

相反的,

let vc = storyboard.instantiateViewController(withIdentifier: 「secondVC") 

使用

let vc = storyboard.instantiateViewController(withIdentifier: 「secondVC") as? YOUR_SECOND_VIEW_CONTROLLER_CLASS_NAME 

並執行任務的步驟在呈現視圖控制器之前如下,

vc?.Var1InSecondViewController = self.var1 
vc?.Var2InSecondViewController = self.var2 
self.present(vc!, animated: true, completion: nil) 
+0

它工作!非常感謝你 ! – Yossi

+0

@Shlomi:歡迎,樂意幫忙:-) – Bharath

0

您可以使用此:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
    if segue.identifier == "yourSegue" { 
     if let firstViewController = segue.destination as? FirstViewController { 
      firstViewController.var1 = var1 
     } 
    } 
} 
} 
相關問題