presentModalViewController from app delegate

前端 未结 3 2201
借酒劲吻你
借酒劲吻你 2021-02-20 09:49

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.

相关标签:
3条回答
  • 2021-02-20 10:06

    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
    
    0 讨论(0)
  • 2021-02-20 10:11

    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:.

    0 讨论(0)
  • 2021-02-20 10:14

    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.

    0 讨论(0)
提交回复
热议问题