Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a view controller created through Storyboard using the App Delegate

I'm working on an iOS5 app using storyboard, and I have a method in a view controller class that i'd like to access from the App Delegate. The trouble is, this view controller gets instantiated via a tab bar controller in storyboard, so the App Delegate has no direct way of calling the method I want...

For a view controller to get in touch with the App Delegate, all one has to do is use:

MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];

Is there a similarly easy way of pointing to an already-instantiated view controller or class?

like image 512
Amos Avatar asked Jan 09 '12 05:01

Amos


People also ask

How do I connect storyboard to ViewController?

Create a new IBOutlet called shakeButton for your storyboard button in your ViewController. swift file. Select the shake button in Interface Builder. Then hold down the control button ( ⌃ ) and click-drag from the storyboard button into your ViewController.


2 Answers

Thanks to Jerry (above), here's the code that got me what I wanted:

    UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
MasterViewController *result;

//check to see if navbar "get" worked
if (navigationController.viewControllers) 

    //look for the nav controller in tab bar views 
    for (UINavigationController *view in navigationController.viewControllers) {

        //when found, do the same thing to find the MasterViewController under the nav controller
        if ([view isKindOfClass:[UINavigationController class]])
            for (UIViewController *view2 in view.viewControllers) 
                if ([view2 isKindOfClass:[MasterViewController class]])                    
                    result = (MasterViewController *) view2;
}
like image 74
Amos Avatar answered Nov 03 '22 00:11

Amos


You'll have to traverse the view hierarchy from the app delegate. Assuming the AppDelegate holds a reference to the UITabBarController, you could use the viewControllers property or selectedViewController property to get to your view controller.

like image 36
Jerry Avatar answered Nov 02 '22 23:11

Jerry