Reputation: 3742
So, switching programatically from one tab in a UITabBarController
to another is easy enough...
self.tabBarController?.selectedIndex = 1
...but hard-coding the tab index each time seems pretty inelegant. It would cause problems if the tabs were re-ordered, for example.
Is there a way to retrieve the [first] index of a specific UIViewController
, so that the code could be something more like the following?
if let destinationIndex = self.tabBarController?.index(of: ExampleViewController) {
self.tabBarController?.selectedIndex = destinationIndex
}
Upvotes: 2
Views: 2344
Reputation: 3742
For those to whom it applies, this is the answer from @Craig Siemens, adapted for when the target VC is embedded in a navigation controller:
if let destinationIndex = self.tabBarController?.viewControllers?.firstIndex(where: {
let navController = $0 as? UINavigationController
return navController?.viewControllers.first is ExampleViewController
}) {
self.tabBarController?.selectedIndex = destinationIndex
}
Upvotes: 0
Reputation: 13296
You'll want to use the firstIndex(where:)
method.
if let destinationIndex = self.tabBarController?.viewControllers.firstIndex(where: { $0 is ExampleViewController }) {
self.tabBarController?.selectedIndex = destinationIndex
}
Upvotes: 7