如何在 UITabBarController 中获取特定 UIViewController 的索引

How to Get Index of Specific UIViewController in UITabBarController

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

self.tabBarController?.selectedIndex = 1

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

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

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

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

if let destinationIndex = self.tabBarController?.viewControllers.firstIndex(where: { [=10=] is ExampleViewController }) {
    self.tabBarController?.selectedIndex = destinationIndex
}

对于适用于它的人,这是@Craig Siemens 的答案,适用于目标 VC 嵌入导航控制器的情况:

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