我从一个视图控制器转到一个tabbarcontroller,我想传递数据。我想把“sendAuthor”传递给tabbarcontroller的第一个视图控制器。

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if segue.identifier == "FirstVC" {

  let vc = (segue.destination as? UITabBarController)?.viewControllers?.first as? CommentProfileViewController

    vc?.sendAuthor = sendAuthor!
    vc?.Username.text = sendAuthor!

        print(sendAuthor!)
    }



    }

为了确保得到正确的结果,我包含了一个print语句print(sendAuthor!),并且得到了正确的print语句。我还在目标视图控制器中包含了print语句,但是print语句返回nil
var sendAuthor: String?

override func viewDidLoad() {
        super.viewDidLoad()
print(self.sendAuthor)

}

最佳答案

你的风险投资是嵌入在UINavigationController中的。你也需要考虑到这一点:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if segue.identifier == "FirstVC" {
       guard let tabbar = segue.destination as? UITabBarController,
             let navcon = tabbar.viewControllers?.first as? UINavigationController,
             let vc = navcon.topViewController as? CommentProfileViewController
             else { return }

       vc.sendAuthor = sendAuthor!
       vc.Username.text = sendAuthor!

       print(sendAuthor!)
    }
}

10-07 20:12