如何在UITabBarController中获取超过5个项目的选定UITabBarItem的标签? [英] How to get the tag of selected UITabBarItem in UITabBarController for more than 5 items?

查看:421
本文介绍了如何在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内有属性itemsselectedItem,但是如果有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
            }
        }
    }
}

这篇关于如何在UITabBarController中获取超过5个项目的选定UITabBarItem的标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆