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
Here is how you do it based on Prashant Tukadiya
's answer.
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)
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 }
Add targetViewControllerID
in the Storyboard ID field.
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