Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dismiss controller and then switch tabs

Tags:

swift

I have two main VC that are in a tab bar controller. On the first VC when you tap a button you are taken to another VC (not the 2nd tab bar VC) and when you tap the finish button I want to go to the 2nd tab bar vc.

Normally I would just perform segue ... but when I do that it removes the tab bar at the bottom. So, I am now just dismissing and going back to the original VC, but I would really like to go to the 2nd tab bar vc so I tried this

dismiss(animated: true) { 
  self.tabBarController?.selectedIndex = 2
}

I saw the self.tabBar... on another SO post, but I can't seem to find where I set the Index...ive tried 1 in case it just automatically starts from 0, and Ive tried 2 in case it starts from 1

Am I close or is there a better way of achieving what I want?

Summary

To summarize clearly. I have 3 View Controllers. 1 and 3 are in a Tab Bar Controller. VC 2 is NOT in the TBC. To get to VC 2 there is a button on VC 1. When the user is finished on VC 2 he/she taps a button. Instead of just dismissing back to VC 1 I want to go to VC 3, but when I perform segue it goes to VC 3 but removes the Tab Bar


1 Answers

Make sure you have a UINavigationController as the first ViewController. Then you have access to the tabBarController and can then switch the tabs:

view controllers

// if vc was pushed
@IBAction func onFinish(_ sender: Any) {
    // store tabBarController for later use
    let tabBarController = self.tabBarController

    // pop to root vc (green one)
    _ = self.navigationController?.popToRootViewController(animated: false)

    // switch to 2nd tab (red vc)
    tabBarController?.selectedIndex = 1
}

// if vc was presented modally
@IBAction func onFinish(_ sender: Any) {
    self.dismiss(animated: false, completion: nil)

    if let tabBarController = self.presentingViewController as? UITabBarController {
        tabBarController.selectedIndex = 1
    }
}

// if vc was presented modally + switching tab in completion block
@IBAction func onFinish(_ sender: Any) {
    if let tabBarController = self.presentingViewController as? UITabBarController {
        self.dismiss(animated: true) {
            tabBarController.selectedIndex = 1
        }
    }
}
like image 190
d.felber Avatar answered Feb 06 '26 07:02

d.felber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!