如何获得UITabBarController中选定的UITabBarItem超过5个项目的标签?

在Storyboard中,我创build了与另一个视图控制器有6个关系的UITabBarController 。 所以现在我有6个UITabBarItems 。 我从05标记他们。 这就是为什么我检测到用户select了什么UITabBarItem

注意:

我不能使用selectedIndex因为这种方式不会告诉我select了哪个tab,因为用户可以更改UITabBar的项目顺序

UITabBar有属性itemsselectedItem但如果有超过5个项目,属性items保持最多5个项目。

例如,当用户在索引45selectUITabBarItem时,对于它们两者,select的索引是4。 现在索引为4UITabBarItem在标签栏上显示“More Items”

所以,我真的需要访问选定的UITabBarItem来获得它的标签 。有没有办法做到这一点?

这是我的情况。

在这里输入图像说明

经过巨大的挖掘,解决scheme相当简单:-)

在符合UINavigationControllerDelegate协议的UITabBarControllerdelegate中:

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

你可以尝试这样的事情

 tabBarController.selectedViewController.view.tag 

因为UIViewController没有标签,但它的视图有。

此外,你可以你UIViewController的属性restorationIdentifier