iOS: How to open 0th Index of tabBarItem by clicking 3rd index of tabBarItem

Viewed 383

I have 5 tabBarItem in my UITabBarController One scenario, I have to open First index of UITabBarItem by clicking third UITabBarItem

My approach as in below:

extension FiveTabbarController: UITabBarControllerDelegate {
    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {

         if item == (self.tabBar.items!)[2] {
             tabBar.selectedItem = (self.tabBar.items!)[0] // ERROR
             self.selectedIndex = 0 // NOT WORKING
         } 

    }
}

Error: *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Directly modifying a tab bar managed by a tab bar controller is not allowed.'

Kindly guide me how to achieve this.

2 Answers

You can achieve the behavior by doing:

func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) { 
    if selectedIndex == 2 {
        self.selectedIndex = 0
    }
}

The reason for the error is because you shouldn't modify the selectedItem, only the index. By modifying the index the tab bar controller will set the selectedItem.

Edited Didn't notice you are using tabBar's method instead of tabbarcontroller's.

You don't want your view controller's base class to be a UITabBarDelegate. If you were to do that, all of your view controller subclasses would be tab bar delegates. What I think you want to do is to extend UITabBarController

class FiveTabbarController: UITabBarController, UITabBarControllerDelegate {

then, in that class, override viewDidLoad and in there set the delegate property to self:

 override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self
    }

now this class is both a UITabBarDelegate (because UITabBarController implements that protocol), and UITabBarControllerDelegate, and you can override/implement those delegate's methods as desired, such as:

    extension FiveTabbarController: UITabBarControllerDelegate {

    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
       if let getSelectedIndex = tabBarController.viewControllers?.firstIndex(of: viewController), getSelectedIndex == 2 {
            self.selectedIndex = 0
        }
    }
}
Related