Ios 准备转到UITabBarController选项卡

Ios 准备转到UITabBarController选项卡,ios,iphone,swift,segue,Ios,Iphone,Swift,Segue,我想将信息从视图控制器传递到UITabBarController,以便我可以从UITabBarController的第三个选项卡中的视图控制器访问某些信息 然而,问题是,当我尝试这样做时,我的程序不断崩溃。以下是我目前的代码: 我这样称呼赛格: self.firstName = user.first_name self.lastName = user.last_name self.performSegueWithIdentifier("OffersView", sender: self) 我重

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

然而,问题是,当我尝试这样做时,我的程序不断崩溃。以下是我目前的代码:

我这样称呼赛格:

self.firstName = user.first_name
self.lastName = user.last_name
self.performSegueWithIdentifier("OffersView", sender: self)
我重写了
prepareforsgue
函数,这样我就可以像这样在这个函数中传递信息:

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帖子,比如


但并没有太大的成功。我是否可能需要创建一个
uitabarcontrollerdelegate
类并通过该类传递信息?任何提示都将不胜感激。谢谢

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

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

它因什么错误消息而崩溃?@rdelmar它似乎没有显示任何特定的错误消息。在一个测试应用程序中,在prepareForSegue中将两个“as”字更改为“as!”后,您的代码对我来说运行良好。您能给我一个如何做到这一点的示例吗?我在“as”字前面加了一个感叹号,但出现了一个错误,说“as后面的预期类型”@rdelmarIt在as后面,as!,以前没有。如何找出选择了哪个选项卡并为特定的选项卡视图设置变量?在我的例子中,我需要导航到“YourViewController”。我猜是在viewControllers数组中存储了所有控制器(我是swift的新手)。