【问题标题】:How to Get Index of Specific UIViewController in UITabBarController如何在 UITabBarController 中获取特定 UIViewController 的索引
【发布时间】:2019-04-12 22:02:50
【问题描述】:

因此,以编程方式从 UITabBarController 中的一个选项卡切换到另一个选项卡很容易...

self.tabBarController?.selectedIndex = 1

...但是每次对标签索引进行硬编码似乎很不优雅。例如,如果重新排序选项卡,则会导致问题。

有没有办法检索特定 UIViewController 的 [first] 索引,以便代码更像以下内容?

if let destinationIndex = self.tabBarController?.index(of: ExampleViewController) {
    self.tabBarController?.selectedIndex = destinationIndex
}

【问题讨论】:

  • 在什么情况下标签索引会被重新排序?
  • 例如开发者的设计变更。

标签: ios swift uiviewcontroller uitabbarcontroller


【解决方案1】:

您需要使用firstIndex(where:) 方法。

if let destinationIndex = self.tabBarController?.viewControllers.firstIndex(where: { $0 is ExampleViewController }) {
    self.tabBarController?.selectedIndex = destinationIndex
}

【讨论】:

  • 完美,谢谢!我没有想过要对 viewControllers 属性进行操作,而不是对 tabBarController 本身进行操作。这就解释了为什么我找不到它。
  • 如果 VC 嵌入在 UINavigationController 中,知道如何使其工作吗?我知道它会使用 .viewControllers.first 是 SuggestionsViewController,但不确定如何将 $0 参数转换为 UINavigationController 以便进行检查。
  • 我解决了:if let destinationIndex = self.tabBarController?.viewControllers?.firstIndex(where: { let navController = $0 as? UINavigationController return navController?.viewControllers.first is ExampleViewController }) { self.tabBarController?.selectedIndex = destinationIndex }
【解决方案2】:

对于那些应用它的人,这是来自@Craig Siemens 的答案,适用于目标 VC 嵌入导航控制器时:

if let destinationIndex = self.tabBarController?.viewControllers?.firstIndex(where: {
    let navController = $0 as? UINavigationController
    return navController?.viewControllers.first is ExampleViewController
}) {
    self.tabBarController?.selectedIndex = destinationIndex
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多