如何获得root视图控制器? [英] How to get root view controller?
本文介绍了如何获得root视图控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个根视图控制器的实例。
I need an instance of root view controller.
我试过这些方法:
UIViewController *rootViewController = (UIViewController*)[[[UIApplication sharedApplication] keyWindow] rootViewController];
返回: null :
当我尝试获取一组控制器时:
Also when I try to get an array of controllers:
NSArray *viewControllers = self.navigationController.viewControllers;
它只返回一个控制器,但它不是我的根视图控制器。
It returns only one controller, but it isn't my root view controller.
如果我尝试从导航控制器获取:
If I try to take from navigation controller:
UIViewController *root = (UIViewController*)[self.navigationController.viewControllers objectAtIndex:0];
返回: null :
任何想法为什么?还有什么我可以尝试获取我的根视图控制器的实例?
Any ideas why? What else could I try to get an instance of my root view controller?
谢谢。
推荐答案
如果您尝试访问在appDelegate中设置的 rootViewController
。试试这个:
if you are trying to access the rootViewController
you set in your appDelegate. try this:
Objective-C
YourViewController *rootController = (YourViewController*)[[(YourAppDelegate*)
[[UIApplication sharedApplication]delegate] window] rootViewController];
Swift
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let viewController = appDelegate.window!.rootViewController as YourViewController
Swift 3
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let viewController = appDelegate.window!.rootViewController as! YourViewController
Swift 4
let viewController = UIApplication.shared.keyWindow!.rootViewController as! YourViewController
这篇关于如何获得root视图控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文