How to get root view controller?

2019-01-13 05:09发布

I need an instance of root view controller.

I tried those approaches:

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

Returns: 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];

Returns: null:

Any ideas why? What else could I try to get an instance of my root view controller?

Thanks.

9条回答
何必那么认真
2楼-- · 2019-01-13 05:40

In short hand way of access root view controller.

Objective C

UIViewController *controller = [UIApplication sharedApplication].keyWindow.rootViewController;

Swift 2.0

let viewController =  UIApplication.sharedApplication().keyWindow?.rootViewController
查看更多
聊天终结者
3楼-- · 2019-01-13 05:50

Swift 3

let rootViewController = UIApplication.shared.keyWindow?.rootViewController

查看更多
Ridiculous、
4楼-- · 2019-01-13 05:52

Unless you have a good reason, in your root controller do this:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(onTheEvent:)
                                             name:@"ABCMyEvent"
                                           object:nil];

And when you want to notify it:

[[NSNotificationCenter defaultCenter] postNotificationName:@"ABCMyEvent"
                                                object:self];                
查看更多
登录 后发表回答