I have a uitabbarcontroller, which contains multiple tabs and viewControllers. I am trying to loop through the view controllers to find the right one and call a method. but the type of the view controller i get, each time i go through the loop is a UINavigationController. So how can i simply access a view controller in my tabBar?
for (UIViewController *v in self.tabBar.viewControllers)
{
if ([v isKindOfClass:[MyViewController class]])
{
MyViewController *myViewController = v;
[v doSomething];
}
}
In Swift 4, to get ViewController from UITabBarController.
let tabBarController : UITabBarController = self.window?.rootViewController as! UITabBarController;
tabBarController.selectedIndex = 0
let navigationController = tabBarController.selectedViewController as! UINavigationController
let controllers = navigationController.viewControllers // will give array
if controllers.count > 0 {
if let viewC = controllers[0] as? DesiredViewController {
// do desired work
}
}
You most likely have UINavigationControllers at the root of your Tabs, so what you will want to do is access the ViewController displayed by the UINavigationController.
Try changing the code to the following:
for (UIViewController *v in self.tabBar.viewControllers) {
UIViewController *vc = v;
if ([v isKindOfClass:[UINavigationController class]]) {
vc = [v visibleViewController];
}
if ([vc isKindOfClass:[MyViewController class]]) {
MyViewController *myViewController = vc;
[vc doSomething];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With