如何获得UITabBarController中选定的UITabBarItem超过5个项目的标签?
在Storyboard中,我创build了与另一个视图控制器有6个关系的UITabBarController
。 所以现在我有6个UITabBarItems
。 我从0到5标记他们。 这就是为什么我检测到用户select了什么UITabBarItem
。
注意:
我不能使用selectedIndex
因为这种方式不会告诉我select了哪个tab,因为用户可以更改UITabBar
的项目顺序 。
在UITabBar
有属性items
和selectedItem
但如果有超过5个项目,属性items
保持最多5个项目。
例如,当用户在索引4或5selectUITabBarItem
时,对于它们两者,select的索引是4。 现在索引为4的UITabBarItem
在标签栏上显示“More Items” 。
所以,我真的需要访问选定的UITabBarItem
来获得它的标签 。有没有办法做到这一点?
这是我的情况。
经过巨大的挖掘,解决scheme相当简单:-)
在符合UINavigationControllerDelegate
协议的UITabBarController
的delegate
中:
//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