10

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];
     }
}
aryaxt
  • 76,198
  • 92
  • 293
  • 442

4 Answers4

20

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];
     }
}
Carl Hine
  • 1,817
  • 18
  • 24
Cameron Hotchkies
  • 1,509
  • 1
  • 13
  • 20
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
vbrittes
  • 200
  • 1
  • 14
1

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
       }
   }
Gurjinder Singh
  • 9,221
  • 1
  • 66
  • 58
0

You don't really want to do this anymore... This is a better case for NSNotificationCenter.

In 2 lines of code, you can get the same things done, without all the extra drama of cycling through view controller arrays. See this post:

NSNotificationCenter addObserver in Swift

Community
  • 1
  • 1
ShowPony
  • 162
  • 1
  • 4