首页 > 解决方案 > 在不知道其索引的情况下选择 UITabBarController 中的特定 viewController

问题描述

我有一个由多个选项组成的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
    }
}

现在,这适用于我目前的情况,因为我知道其中的第二项tabBarControllerUIViewController我正在寻找的,但我想对我的应用程序进行未来验证,以便如果将来更改viewControllers的顺序, tableView会不破。tabBarController

换句话说,我想知道是否有一种方法可以首先从中提取我要查找的viewControllertabBarController的索引,然后使用该索引导航到它,如下所示:

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 */
    }
 }

标签: iosswiftuitabbarcontroller

解决方案


您可以尝试以下方法:

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
    }
}

推荐阅读