ios 如何从 AppDelegate 上的 TabBarController 获取 ViewController?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10688848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:28:04  来源:igfitidea点击:

How can I get ViewController from TabBarController on AppDelegate?

iphoneiosipadios5

提问by Ariel Zehao Zhang

I use iOS5 storyboard, and my initial view controller is TabBarController, there are four relationships to view1 & view2 & view3 & view4, so, how can I get the view3's view controller?

我使用iOS5 storyboard,我的初始视图控制器是TabBarController,view1&view2&view3&view4有四个关系,那么,我怎样才能得到view3的视图控制器?

I tried:

我试过:

[[[[self.window.rootViewController navigationController] tabBarController] viewControllers] objectAtIndex:2];

But it doesn't work...

但它不起作用...

回答by Dima

You said that your initial (root) view controller is a UITabBarController but you are referring to a view controller with a navigation controller with a tab bar controller. Are you getting mixed up in your view controller hierarchy?

你说你的初始(根)视图控制器是一个 UITabBarController 但你指的是一个带有导航控制器和标签栏控制器的视图控制器。您是否在视图控制器层次结构中混淆了?

edit:

编辑:

if your root view controller is actually just a tab bar controller and you want to get the 3rd tab here is the code:

如果您的根视图控制器实际上只是一个标签栏控制器,并且您想获得第三个标签,则代码如下:

[[((UITabBarController *)self.window.rootViewController) viewControllers] objectAtIndex:2];

回答by Haider

[self.tabBarController setSelectedIndex:2];

回答by Tunvir Rahman Tusher

Try this way

试试这个方法

In any view controller

在任何视图控制器中

 YourViewController *yourViewController= (YourViewController*)  [self.tabBarController.viewControllers objectAtIndex:3];

this return your that view controller object.Cast it to your view controller and you are ready to use that. run and Go

这将返回您的视图控制器对象。将它投射到您的视图控制器,您就可以使用它了。跑去

回答by vilas

   UIViewController *loginViewController=self.window.rootViewController;

   UITabBarController *controller=loginViewController.tabBarControllerObj;

   UIViewController *selectedController=controller.selectedViewController;

From this you will get selected view controller.

从中您将获得选定的视图控制器。

For getting all view controller just replace

要获取所有视图控制器,只需替换

NSArray *viewControllers = [controller viewControllers];

回答by Gurjinder Singh

Swift 4.0

斯威夫特 4.0

let viewC = self?.tabBarController.viewControllers.first // will give single Navigation Controller on index 0
let viewC = self?.tabBarController?.viewControllers// will give array of Navigation Controller

Further you can check the Visible ViewController

此外,您可以检查 Visible ViewController

if let nav = viewC as? UINavigationController {
   if nav.visibleViewController is YourViewControllerName{
        // Do Code
     }
}