在 Storyboard 中,我创建了 UITabBarController
,它与另一个 View Controller 有 6 个关系。所以现在我有 6 个 UITabBarItems
。我将它们标记为从 0 到 5。这就是为什么我检测到用户选择了 UITabBarItem
的原因。
注意:
我不能使用 selectedIndex
因为这种方式不会告诉我选择了哪个选项卡,因为用户可以更改 UITabBar
中项目的顺序/strong>.
在 UITabBar
中有属性 items
和 selectedItem
但如果超过 5 个项目,属性 items
最多保留 5 项。
例如,当用户在索引4 或5 处选择UITabBarItem
时,两者选择的索引都是4。现在,索引为 4 的 UITabBarItem
指示标签栏上的 “更多项目”。
所以,我确实需要访问选定的 UITabBarItem
以获取其标签。有什么办法可以做到这一点吗?
这是我的情况。
最佳答案
经过大量挖掘,解决方案相当简单:-)
在符合 UINavigationControllerDelegate
协议(protocol)的 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
}
}
}
}
关于ios - 如何获取超过 5 个项目的 UITabBarController 中选定的 UITabBarItem 的标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31521951/