在不知道其索引的情况下在UITabBarController中选择特定的viewController

时间:2018-11-09 15:05:28

标签: ios swift uitabbarcontroller

我有一个由许多选项组成的 UItabBarController (称为tabBarController)。我还有一个 UITableView ,其第一行是一个选项,应使用户导航到特定的 viewController

我的didSelectRowAt委托方法如下:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    if tableView.cellForRowAt(at: indexPath)?.textLabel?.text == "Navigate to BrowseViewController" {
        /* BrowseViewController is currently the second item in the 
           tabBarController, so I just select its index to navigate to it */
        tabBarController?.selectedIndex = 2
    }
}

现在,这适用于我当前的情况,因为我知道tabBarController中的第二个项目是我正在寻找的UIViewController,但我希望未来-验证我的应用程序,以便将来更改tabBarController viewControllers 的顺序时, tableView 不会中断。

换句话说,我想知道是否有一种方法可以首先从tabBarController中提取要查找的 viewController 的索引,然后使用该索引导航到它,就像这样:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    if tableView.cellForRowAt(at: indexPath)?.textLabel?.text == "Navigate to BrowseViewController" {

        let browseViewControllerIndex = Int()
        /* iterate through tabBarController's VC's and if the type of the VC 
       is BrowseViewController, find its index and store it
       in browseViewController */
    }
 }

2 个答案:

答案 0 :(得分:1)

您可以尝试以下操作:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    if tableView.cellForRowAt(at: indexPath)?.textLabel?.text == "Navigate to BrowseViewController" {

        // safely get the different viewcontrollers of your tab bar
        // (viewcontrollers is an optional value)
        guard let tabs = tabBarController.viewcontrollers else { return }

        // index(of:) gets you the index of the specified class type.
        // Also an optional value
        guard let index = tabs.index(of: BrowseViewController()) else { return }
        tabBarController?.selectedIndex = index
    }
}

答案 1 :(得分:1)

我能够自己解决这个问题。以下代码最适合 my 目标。 (我认为)它相当简洁,优雅:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    if tableView.cellForRowAt(at: indexPath)?.textLabel?.text == "Navigate to BrowseViewController" {

        if let browseIndex = (tabBarController?.viewControllers?.filter { $0 is UINavigationController} as? [UINavigationController])?.firstIndex(where: { $0.viewControllers.first is BrowseViewController }) {
            tabBarController?.selectedIndex = browseIndex
        }

    }

}

请注意,BrowseViewControllerUINavigationController的第一个 viewController 。当然,查看此答案的用户应修改其代码以适合其体系结构。

相关问题