准备Segue到UITabBarController选项卡

时间:2015-04-11 00:44:23

标签: ios iphone swift segue

我想将信息从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 prepareforseguePass data from tableview to tab bar view controller in Swift.但没有取得多大成功。我是否可能需要创建一个UITabBarControllerDelegate类并通过它传递信息?任何提示将不胜感激。谢谢!

3 个答案:

答案 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
            }
        }
    }
}