Search code examples
iosswiftxcodeuitabbarcontrolleruitabbar

How to reset tab (or tab controller) of UITabBarController when user select tab?


Swift: I have UITabBarController, with 8 tabs. When user select any tab including more tab, I want reset content of selected tab by Popping to rootView controller?

How could this be done?

I tried to reset navigation controllers in below methods, It works for tabs which are visible at bottom but it doesn't work for More tab.

tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) 

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem)

Solution

  • A clean way to do this:

    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        let index = tabBarController.selectedIndex
        if index == NSNotFound || index > 4 {
            tabBarController.moreNavigationController.popToRootViewController(animated: false)
            return
        }
        let navController = tabBarController.viewControllers?[tabBarController.selectedIndex] as? UINavigationController
        navController?.popToRootViewController(animated: false)
    }
    

    Create a custom class for your UITabViewContoller, set a delegate and put there that piece of code.