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.
if you are trying to access the
rootViewController
you set in your appDelegate. try this:Objective-C
Swift
Swift 3
Swift 4
Swift way to do it, you can call this from anywhere, it returns optional so watch out about that:
Its included as a standard function in:
https://github.com/goktugyil/EZSwiftExtensions
Swift 3: Chage ViewController withOut Segue and send AnyObject Use: Identity MainPageViewController on target ViewController
or if you want to Change View Controller and send Data
As suggested here by @0x7fffffff, if you have UINavigationController it can be easier to do:
The code in the answer above returns UINavigation controller (if you have it) and if this is what you need, you can use
self.navigationController
.Objective-C format :
Swift 2 format :
Swift 3 and 4 format :