ios - 在不知道其索引的情况下选择 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
}
}
现在,这适用于我目前的情况,因为我知道其中的第二项tabBarController
是UIViewController
我正在寻找的,但我想对我的应用程序进行未来验证,以便如果将来更改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 */
}
}
解决方案
您可以尝试以下方法:
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
}
}
推荐阅读
- apache-spark - 使用 PySpark 生成 6000 万个 JSON 文件时出现 OutOfMemoryError
- php - 通过 eloquent 关系删除行
- javascript - 如何使用 javascript 中的 fetch 命令获取 json 并将其添加到数组中
- xquery - 检索 XML 子集
- c# - 使用 SMPT 客户端发送带有日历邀请的电子邮件
- gcc - 在 debian 中安装 arm-gcc 4.9 版本
- partitioning - 如何在 DolphinDB 中删除复合分区
- python - 在熊猫数据框的特定列上应用 PCA
- java - ApachePOI 从 RichTextString 中提取数字
- opencv - 卸载 opencv 但 pkg-config 仍然显示版本号