adit
adit

Reputation: 33644

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.

Upvotes: 11

Views: 14711

Answers (3)

Steve
Steve

Reputation: 31642

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

Upvotes: 10

XJones
XJones

Reputation: 21967

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.

Upvotes: 12

Mark Adams
Mark Adams

Reputation: 30846

Application delegates do not manage a view. You should present a modal view controller from the -viewDidAppear: method of the first view controller that gets put on screen in -application:didFinishLaunchingWithOptions:.

Upvotes: 6

Related Questions