如何在UITabBarController中获取超过5个项目的选定UITabBarItem的标签?
在情节提要中,我创建了UITabBarController
,它与另一个视图控制器具有6种关系.所以现在我有6个UITabBarItems
.我将它们从 0 标记为 5 .这就是为什么我检测到用户选择了UITabBarItem
的原因.
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.
注意:
我无法使用selectedIndex
,因为用户可以更改UITabBar
中的项目顺序,因此这种方式不会告诉我选择了哪个选项卡.
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
.
在UITabBar
内有属性items
和selectedItem
,但是如果有5个以上的项目,则属性items
最多保留 5 个项目.
Within UITabBar
there is property items
and selectedItem
but if there is more than 5 items, the property items
keeps max 5 items.
例如,当用户在索引 4 或 5 中选择UITabBarItem
时,两个索引均选择为4.现在,索引为 4 的UITabBarItem
在选项卡栏更多项目" 中指示.
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".
因此,我真的需要访问所选的UITabBarItem
以获得其标签.有什么方法可以做到这一点?
So, I really need to access to the selected UITabBarItem
to get its tag.Is there any way to do this?
这是我的情况.
经过大量挖掘,解决方案非常简单:-)
After a huge digging, the solution is fairly simple:-)
:
//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
}
}
}
}