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

血红的双手。 提交于 2019-12-02 06:25:11

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

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

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