简体   繁体   中英

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
}

You'll want to use the firstIndex(where:) method.

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

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
}

Create an enum for your tabbar items.

If design changes the order, you can change it in the enum without changing anything else.

enum TabbarVCs: Int {
 case home
 case settings
 case profile
}

tabBarController.selectedIndex = TabbarVCs.home.rawValue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM