Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with Modal View Controllers and definesPresentationContext

I've created a custom container view controller using the new UIViewController container view controller methods in iOS 5.

Trouble is, even though my container controller's child UIViewController has definesPresentationContext = YES, when it creates and presents another modal view controller, UIKit sets the container (rather than the child) as the presenting controller.

For example, in MyChildViewController.m:

- (void)showMailComposeView:(id)sender {

    __block MFMailComposeViewController *vc =
            [[MFMailComposeViewController alloc] init];
    vc.mailComposeDelegate = self;
    vc.subject = @"Subject";

    self.definesPresentationContext = YES;

    [self presentViewController:vc animated:YES completion:^{

       if ([self.modalViewController isEqual:vc])
            NSLog(@"This should print...");

       if ([vc.presentingViewController isEqual:self.parentViewController])
            NSLog(@"... but this shouldn't");

       // NOTE: Both log statements printed

    }];
}

- (void)mailComposeController:(MFMailComposeViewController*)controller
          didFinishWithResult:(MFMailComposeResult)result
                        error:(NSError*)error
{ 
    [self dismissViewControllerAnimated:YES completion:^{}];

    // NOTE: self.parentViewController.view now displays instead of self.view
}

Where am I going wrong?

How do I ensure it's the child view which gets revealed when the modal view gets dismissed (rather than the container view)?

like image 416
followben Avatar asked Oct 28 '11 00:10

followben


1 Answers

Add this line before presenting the view controller:

vc.modalPresentationStyle = UIModalPresentationCurrentContext

If you've done all the correct parent-child things all the way up the view controller chain, this will cause the presented view to replace the MyChildViewController's view, and then the MyChildViewController's view will return when the presented view is dismissed.

Oh, and I forgot to mention, even then this will work only on iPad. A presented view controller's view always occupies the whole screen on iPhone - it is always presented from the root view.

EDIT: Starting in iOS 8, this feature is also available on iPhone. (And so are popovers and split views - basically, most statements of the form "only on iPad" became false with iOS 8, which in my view is awesome news.)

like image 188
matt Avatar answered Dec 06 '22 08:12

matt