Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

presentModalViewController from app delegate

How can I present a modal view controller from the app delegate's view, the top most? Trying to present a modal view controller from a UIView, which made me confused.

like image 343
adit Avatar asked Jan 11 '12 19:01

adit


Video Answer


2 Answers

Use your rootViewController. You can present a modal view controller from any view controller subclass. If your root VC is a UITabBarController, then you can do:

[self.tabBarController presentModalViewControllerAnimated:YES]

or if its a navigation controller:

[self.navigationController presentModalViewControllerAnimated:YES]

etc.

EDIT: MVC

By trying to present a controller from within a view you are breaking the MVC pattern. Generally, a view is concerned with its appearance and exposing interfaces to communicate user interface state to its controller. For example, if you have a UIButton in your view and you want it to present a modal view controller, you don't hard wire the view to do this. Instead, when a controller instantiates the view, the controller configures the button by setting itself as a target to receive the touchUpInside action where it can present the appropriate modal view controller.

The view itself does not (and should not) have this contextual knowledge to do the work of a controller.

like image 106
XJones Avatar answered Oct 28 '22 03:10

XJones


The best way to do this is to create a new UIWindow, set it's windowLevel property, and present your UIViewController in that window.

This is how UIAlertViews work.

Interface

@interface MyAppDelegate : NSObject <UIApplicationDelegate>

@property (nonatomic, strong) UIWindow * alertWindow;

...

- (void)presentCustomAlert;

@end

Implementation:

@implementation MyAppDelegate

@synthesize alertWindow = _alertWindow;

...

- (void)presentCustomAlert
{
    if (self.alertWindow == nil)
    {
        CGRect screenBounds = [[UIScreen mainScreen] bounds];
        UIWindow * alertWindow = [[UIWindow alloc] initWithFrame:screenBounds];
        alertWindow.windowLevel = UIWindowLevelAlert;
    }

    SomeViewController * myAlert = [[SomeViewController alloc] init];
    alertWindow.rootViewController = myAlert;

    [alertWindow makeKeyAndVisible];
}

@end
like image 28
Steve Avatar answered Oct 28 '22 03:10

Steve