Search code examples
iosswiftuinavigationcontrolleruitabbarcontrollerselectedindex

Switch Tabs and Reset Nav's View Controllers at the same time-Swift iOS


I have a tabBarController with 2 tabs:

tab0, tab1

In tab0 I have a navigationController with 3 child views

viewA (root), viewB, viewC

pressing a button in viewC will bring me to tab1 using code

@IBAction func switchButtonTapped(sender: UIButton){
    tabBarController.selectedIndex = 1
}

The problem I'm having is that once I switch to tab1 I can't get tab0 to reset back to viewA (its root vc), it stays on viewC.

How do I switch from tab0 to tab1 and at the same time reset the views in tab0?

Since I'm simultaneously switching tabs and resetting a nav controller's vcs should this happen on different threads?

 @IBAction func switchButtonTapped(sender: UIButton){
        tabBarController.selectedIndex = 1
        dispatch_async(dispatch_get_main_queue(), {
self.navigationController?.popToRootViewController(animated:true)
} 
    }

Solution

  • Note: Swift 3 Code:

    @IBAction func switchButtonTapped(sender: UIButton){
        tabBarController?.selectedIndex = 1
        navigationController?.popToRootViewController(animated: true)
    }
    

    This works fine for me (it selects the second tab and when I tap on the first tab button, It shows the root -first- ViewController for the first tab).