iosswiftuinavigationcontrollertabbarcontroller

Go to a nested ViewController from a main TabBarController programmatically in Swift


I have the following ViewController structure, see image below.

Whenever I want to move from ViewController 1 to any of the other main controllers I use self.tabBarController?.selectedIndex = indexNumber

// for instance, this would take me to ViewController 3
self.tabBarController?.selectedIndex = 2

Based on the picture below, how can I go from ViewController 1 to TargetViewController programmatically when a button is tapped in ViewController 1?

FYI - In the picture below I'm showing a button in ViewController 3 this is just to show the storyboard structure, the actual button-tap will happen in ViewController 1

enter image description here

EDIT:

Here is how you do it based on Prashant Tukadiya's answer.

ViewController 1

In ViewController 1 add the following in your tap event.

    self.tabBarController?.selectedIndex = 2
    let nav = (self.tabBarController?.viewControllers?[2] as? UINavigationController)
    let vc =  TargetViewController.viewController()
    nav?.pushViewController(vc, animated: true)

TargetViewController

  1. In your TargetViewController add the following class method.

    class func viewController() -> TargetViewController { let storyboard = UIStoryboard(name: "Main", bundle: nil) return storyboard.instantiateViewController(withIdentifier: "targetViewControllerID") as! TargetViewController }

  2. Add targetViewControllerID in the Storyboard ID field.


Solution

  • You can directly give identifier to the TargetViewController from storyboard and load from storyboard then and push or present it.

    like add this method in your TargetViewController

    class func viewController () ->  TargetViewController {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        return storyboard.instantiateViewController(withIdentifier: "yourIdentifer") as! TargetViewController
    }
    

    and on tap event

         let vc =  TargetViewController.viewController()
    
        self.navigationController?.pushViewController(vc, animated: true)
    

    EDIT

    After reading comments got clear idea about your requirements

    On button action from ViewController1, You want to goto TargetViewController but when press back you want back to viewController 3

    Select particular index first

       self.tabBarController?.selectedIndex = 2
    

    After that you need to grab UINavigationController

    let nav = (self.tabBarController?.viewControllers?[2] as? UINavigationController)
    

    then Push ViewController

        let vc =  TargetViewController.viewController()
    
        nav?.pushViewController(vc, animated: true)
    

    Note: Don't forgot add identifier to storyboard to TargetViewController and also add class func viewController () -> TargetViewController method to TargetViewController

    Hope it is helpful