一尘不染

如何获得根视图控制器?

swift

我需要一个根视图控制器实例。

我尝试了这些方法:

UIViewController *rootViewController = (UIViewController*)[[[UIApplication sharedApplication] keyWindow] rootViewController];

返回: null

另外,当我尝试获取控制器数组时:

NSArray *viewControllers = self.navigationController.viewControllers;

它仅返回一个控制器,但不是我的根视图控制器。

如果我尝试从导航控制器中获取:

UIViewController *root = (UIViewController*)[self.navigationController.viewControllers objectAtIndex:0];

返回: null

有什么想法吗?我还能尝试获得根视图控制器的一个实例吗?

谢谢。


阅读 251

收藏
2020-07-07

共1个答案

一尘不染

如果您尝试访问rootViewController在appDelegate中设置的。试试这个:

目标C

YourViewController *rootController = (YourViewController*)[[(YourAppDelegate*)
                                   [[UIApplication sharedApplication]delegate] window] rootViewController];

迅速

let appDelegate  = UIApplication.sharedApplication().delegate as AppDelegate
let viewController = appDelegate.window!.rootViewController as YourViewController

迅捷3

let appDelegate  = UIApplication.shared.delegate as! AppDelegate
let viewController = appDelegate.window!.rootViewController as! YourViewController

迅捷4和4.2

let viewController = UIApplication.shared.keyWindow!.rootViewController as! YourViewController

雨燕5&5.1&5.2

let viewController = UIApplication.shared.windows.first!.rootViewController as! YourViewController
2020-07-07