我想将信息从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
(在上面代码的第二行)时,我的代码崩溃了。我不确定为什么我会查看很多StackOverflow帖子,例如
Swift tab bar view prepareforsegue和Pass data from tableview to tab bar view controller in Swift.但没有取得多大成功。我是否可能需要创建一个UITabBarControllerDelegate
类并通过它传递信息?任何提示将不胜感激。谢谢!
答案 0 :(得分:9)
在讨论之后发现的问题是标签栏控制器的子项嵌入在导航控制器中,因此需要将代码更改为此,
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
}
答案 1 :(得分:3)
在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
答案 2 :(得分:0)
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
}
}
}
}