Search code examples
iosuitabbarcontrolleruitabbaritem

How to get the tag of selected UITabBarItem in UITabBarController for more than 5 items?


In Storyboard I created UITabBarController with 6 relationships to another view controllers. So now I have 6 UITabBarItems. I tagged them from 0 to 5. This is why I detect what UITabBarItem was selected by user.

NOTE:

I cannot use selectedIndex because this way doesn't tell me what tab was chosen, since user IS ABLE to change the order of items in UITabBar.

Within UITabBar there is property items and selectedItem but if there is more than 5 items, the property items keeps max 5 items.

For instance when user choose UITabBarItem at index 4 OR 5, selected Index is 4 for both of them. Now the UITabBarItem with index 4 indicates on tab bar "More Items".

So, I really need to access to the selected UITabBarItem to get its tag.Is there any way to do this?

This is my situation.

enter image description here


Solution

  • After a huge digging, the solution is fairly simple:-)

    within your UITabBarController's delegate that conforms to UINavigationControllerDelegate protocol:

    //MARK: - UITabBarControllerDelegate
    
    func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
    
        if viewController == tabBarController.moreNavigationController {
            tabBarController.moreNavigationController.delegate = self
        } else {
            findSelectedTagForTabBarController(tabBarController)
        }
    }
    
    //MARK: - UINavigationControllerDelegate
    
    func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) {
        findSelectedTagForTabBarController(navigationController.tabBarController)
    }
    
    //MARK: - Private
    
    private func findSelectedTagForTabBarController(tabBarController: UITabBarController?) {
    
        if let tabBarController = tabBarController {
            if let viewControllers = tabBarController.viewControllers {
                let selectedIndex = tabBarController.selectedIndex
                let selectedController: UIViewController? = viewControllers.count > selectedIndex ? viewControllers[selectedIndex] : nil
                if let tag = selectedController?.tabBarItem.tag {
                    //here you can use your tag
                }
            }
        }
    }