iosobjective-cmodalviewcontrollerkeywindow

How to Present a Modal above a View that was added to keyWindow?


I have added a view to [[UIApplication sharedApplication] keyWindow], because we want it to overlap the navigation bar.

Now we want to tap a button on the view and open a window modally, ideally by using presentViewController. Is there a way to make this modal view appear above (on the z-axis) the keyWindow view?

My Answer

I ended up adding my first custom UIViewController to self.tabBarController. This allows the UIViewController to overlap the Navigation Bar and the Tab Bar.

Then I use [self.navigationController presentViewController:animated:completion] to present the modal, which is above everything else on the z-axis.

Here is the code for adding the UIViewController to the self.tabBarController

        MyCustomViewController * overlayView = [[MyCustomViewController alloc]
                      initWithNibName:@"MyCustom"
                      bundle:nil];

        UIViewController *parentViewController = self.tabBarController;
        [modalView willMoveToParentViewController:parentViewController];

        // set the frame for the overlayView
        overlayView.view.frame = parentViewController.view.frame;

        [parentViewController.view addSubview: overlayView.view];

        [parentViewController.view needsUpdateConstraints];
        [parentViewController.view layoutIfNeeded];

        // Finish adding the overlayView as a Child View Controller
        [parentViewController addChildViewController: overlayView];
        [overlayView didMoveToParentViewController:parentViewController];

Solution

  • You should rethink the way you're adding the overlay view.

    If you want a view to overlap the navigation bar you could just add this view as a top subview of the navigation bar. Or you could add it as a top subview of the navigation controller view.