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

耗尽温柔 提交于 2019-12-02 11:16:11

问题


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.


回答1:


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
            }
        }
    }
}



回答2:


You can try something like this

tabBarController.selectedViewController.view.tag

as the UIViewController does not have tag, BUT its view has.

Also, you can you UIViewController's property restorationIdentifier



来源:https://stackoverflow.com/questions/31521951/how-to-get-the-tag-of-selected-uitabbaritem-in-uitabbarcontroller-for-more-than

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!