UITabBarController - How to access a view controll

2020-02-09 04:47发布

问题:

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];
     }
}

回答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];
     }
}


回答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


回答3:

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



回答4:

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
       }
   }