Ahad Sheriff Ahad Sheriff - 2 months ago 9
Swift Question

prepareForSegue when embedding Tab Bar Controller into Navigation Controller

I currently have a navigation controller setup like this:

enter image description here

and my prepareForSegue, that passes data between the initial view (Login View Controller) and the Navigation controller looks like such:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
super.prepareForSegue(segue, sender: sender)
let navVc = segue.destinationViewController as! UINavigationController // 1
let chatVc = navVc.viewControllers.first as! ChatViewController // 2
chatVc.senderId = userID // 3
chatVc.senderDisplayName = "" // 4
}


However, when I try to embed in a Tab Bar controller (to add more pages/functionality to my app) like this...

enter image description here

...and run my application, my program crashes at the line
let navVc = segue.destinationViewController as! UINavigationController


I know that the problem is that after my initial view, it goes to the tab bar which is type
UITabBarController
rather than
UINavigationController
however if I change it, my data does not go to the view that I want it to go to...it is kind of confusing.

Please let me know if you have any ideas how to implement this, or if you have any questions feel free to ask me for clarification.

Thanks!

P.s. The error that I am receiving in the console is:

Could not cast value of type 'UITabBarController' (0x10b8e48b0) to 'UINavigationController' (0x10b8e4860).

Answer

Try this:

Start by casting destinationViewController to UITabBarController and then using the viewControllers property to access the first viewController in the tabBarController:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    let tabVc = segue.destinationViewController as! UITabBarController
    let navVc = tabVc.viewControllers!.first as! UINavigationController
    let chatVc = navVc.viewControllers.first as! ChatViewController
    chatVc.senderId = userID
    chatVc.senderDisplayName = ""
}
Comments