我正在尝试将数据传递给第二个视图控制器,但没有成功
这是我的代码:
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 :(得分: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)
答案 1 :(得分:0)
您可以使用:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "yourSegue" {
if let firstViewController = segue.destination as? FirstViewController {
firstViewController.var1 = var1
}
}
}
}