TheNeil
TheNeil

Reputation: 3742

How to Get Index of Specific UIViewController in UITabBarController

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

Answers (2)

TheNeil
TheNeil

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

Craig Siemens
Craig Siemens

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

Related Questions