airsoftFreak airsoftFreak - 3 months ago 6x
Swift Question

How to instantiate a navigation and tab controller from another view controller which is in segue(show detail)?

I've asked a question before and it works successfully thanks to the one of the answers How to instantiate a navigation controller from another view controller?, but I have come across a new problem which is , whenever i click a button from a show detail segue, it supposed to navigate to a normal tab with a navigation bar, but it did nothing.

Here's the storyboard

enter image description here

Here's the scenario

1) User click on a button on a firstViewController and it will segue to a thirdViewController which is in show detail

2) User click another button which will then supposed to go to a secondViewController with the codes below

Here's the code

in ThirdViewController

@IBAction func buttonTapped(sender: UIButton) {

guard let tabBarController = tabBarController else { return }
let navController = tabBarController.viewControllers![1] as! UINavigationController
let secondViewController = navController.topViewController as! SecondViewController = "My name is TDog"

tabBarController.selectedIndex = 1


What did i do wrong? Do i still need to instantiate?


You have to dismiss the actual ThirdViewController but, in this class, you dont know yet UITabViewController so a way to obtain it ( not to re-instantiate but to recall from memory) is to call the rootViewController of your window (it can be done in your project):

@IBAction func buttonTapped(sender: AnyObject) {
    self.presentingViewController!.dismissViewControllerAnimated(true, completion: nil)
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let tabBarController = appDelegate.window!.rootViewController
    if tabBarController is UITabBarController {
        let tab = tabBarController as! UITabBarController
        let navController = tab.viewControllers![1] as! UINavigationController
        let secondViewController = navController.topViewController as! SecondViewController
        secondViewController.nameString = "My name is TDog"
        tab.selectedIndex = 1