UITabBarController - How to access a view controller?
19,473
Solution 1
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];
}
}
Solution 2
This can be achieved in swift in a using an array filter:
var vc = tabBar.viewControllers!.filter({ (v) -> Bool in
return (v is YourViewController)
})[0] as! UINavigationController
Solution 3
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
}
}
Author by
aryaxt
Updated on June 27, 2022Comments
-
aryaxt almost 2 years
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]; } }