Swift:将数据从视图控制器传递到导航控制器

时间:2019-05-17 15:39:12

标签: swift viewcontroller navigationcontroller

我想将数据从一个视图控制器传递给另一个控制器,但是它们之间有一个导航控制器,所以有一个“ present”功能而不是“ performSegue”。

 private func IniciarMainAdmin(){
    let mainAdmin = UIStoryboard(name: "Main", bundle: Bundle.main)
    guard let mainAdminNVC = mainAdmin.instantiateViewController(withIdentifier: "NCMainAdmin") as? NCMainAdmin else{
        return
    }
    present(mainAdminNVC, animated: true, completion: nil)
}

我已经尝试过使用此代码,但对我而言不起作用:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let destViewController = segue.destination as! NCMainAdmin
        let secondViewcontroller = destViewController.viewControllers.first as! NCMenuAdmin
        secondViewcontroller.adminUserData = "This is a test"
}

注意:

  • NCMainAdmin是导航控制器
  • NCMenuAdmin是导航控制器的第一个视图控制器

谢谢!

1 个答案:

答案 0 :(得分:0)

要触发代码prepare(for,您需要创建一个从发送方vc到导航的序列,

 private func IniciarMainAdmin(){
    let mainAdmin = UIStoryboard(name: "Main", bundle: Bundle.main)
    guard let mainAdminNVC = mainAdmin.instantiateViewController(withIdentifier: "NCMainAdmin") as? NCMainAdmin else{
        return
    }
    let first = mainAdminNVC.viewControllers.first as! NCMenuAdmin
    first.adminUserData = "This is a test"
    present(mainAdminNVC, animated: true, completion: nil)
}

OR

self.performSegue(withIdentifier:"id",sender:nil)

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let destViewController = segue.destination as! NCMainAdmin
        let secondViewcontroller = destViewController.viewControllers.first as! NCMenuAdmin
        secondViewcontroller.adminUserData = "This is a test"
}