Search code examples
iosswiftxcodeuinavigationcontrolleruitabbarcontroller

Tapping on a tabBar item should always open the first view controller


I have an application with a tab bar navigation (5 buttons). Is it possible to always open the first controller of the navigation when tapping on one of the 5 tab bar buttons? For example, button1 opens VC1 (with navigation controller), which can open VC2, which can open VC3, etc. And if I am on VC3, then click on another tab bar button (let's say button2), then again click on button1, I want it to open VC1, not VC3 where I left it.

I tried with this, but for some reason it's not working like I expect:

func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
    self.navigationController?.popToRootViewController(animated: true)
    viewController.navigationController?.popToRootViewController(animated: true)
}

Solution

  • To achieve this functionality, I write the code in didSelect method of tabBarDelegate.

    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
                let rootView = self.viewControllers![self.selectedIndex] as! UINavigationController
                rootView.popToRootViewController(animated: false)
         }