准备Segue到UITabBarController选项卡

我想将信息从ViewController传递到UITabBarController以便我可以从UITabBarController的第3个选项卡中的视图控制器访问某些信息。

但问题是,当我尝试这样做时,我的程序一直在崩溃。 这是我到目前为止的代码:

我这样称呼segue:

 self.firstName = user.first_name self.lastName = user.last_name self.performSegueWithIdentifier("OffersView", sender: self) 

我覆盖prepareForSegue函数,以便我可以像这样在这个函数中传递信息:

 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "OffersView"){ let barViewControllers = segue.destinationViewController as UITabBarController let destinationViewController = barViewControllers.viewControllers![2] as ProfileController destinationViewController.firstName = self.firstName destinationViewController.lastName = self.lastName } } 

当我尝试设置destinationViewController (在上面代码的第二行)时,我的代码崩溃了。 我不知道为什么我看了很多StackOverflowpost,比如

Swift标签栏视图prepareforsegue并将数据从tableview传递到Swift中的标签栏视图控制器。 但没有取得多大成功。 我是否可能需要创建一个UITabBarControllerDelegate类并通过它传递信息? 任何提示将不胜感激。 谢谢!

讨论后发现的问题是标签栏控制器的子项嵌入在导航控制器中,因此需要将代码更改为此,

 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let barViewControllers = segue.destinationViewController as! UITabBarController let nav = barViewControllers.viewControllers![2] as! UINavigationController let destinationViewController = nav.topviewcontroller as ProfileController destinationViewController.firstName = self.firstName destinationViewController.lastName = self.lastName } 

在swift 3中,xcode 8代码就像

 let barViewControllers = segue.destination as! UITabBarController let nav = barViewControllers.viewControllers![0] as! UINavigationController let destinationViewController = nav.viewControllers[0] as! YourViewController destinationViewController.varTest = _varValue 

Swift 4解决方案无需强制可选展开

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let barVC = segue.destination as? UITabBarController { barVC.viewControllers?.forEach { if let vc = $0 as? YourViewController { vc.firstName = self.firstName vc.lastName = self.lastName } } } }