Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITabBarController - How to access a view controller?

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];
     }
}
like image 614
aryaxt Avatar asked Nov 29 '10 18:11

aryaxt


2 Answers

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
       }
   }
like image 53
Gurjinder Singh Avatar answered Sep 21 '22 16:09

Gurjinder Singh


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];
     }
}
like image 38
Cameron Hotchkies Avatar answered Sep 22 '22 16:09

Cameron Hotchkies