首页 > 解决方案 > 如何在 UITabBarController 中获取特定 UIViewController 的索引

问题描述

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

self.tabBarController?.selectedIndex = 1

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

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

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

标签: iosswiftuiviewcontrolleruitabbarcontroller

解决方案


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

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

推荐阅读