Search code examples
iosobjective-cios7uiviewcontrollerios8

How to pass parameters from a modal viewcontroller?


I have two viewcontrollers. Here is the second one:

UIViewController *modal = [[ModalViewController alloc]init];
[self presentViewController:modal animated:YES completion:nil];

Second modal window:

[self dismissViewControllerAnimated:YES completion:nil];

How do I pass parameters from a modal view controller?


Solution

  • If I understand you correctly, you would like to make / tell the presenting controller to dismiss the modal view controller from the modal view controller?

    I gather that being the reason why you thought of passing self as "parameter" to the modal view controller, so that it could reference it and make it dismiss the ModalViewController through the use of [self dismissViewControllerAnimated:YES completion:nil]; as you mentioned?

    If so, you could make use of protocol:

    In your modal view controller's header file (.h), declare:

    @protocol ModalViewControllerProtocol
    
    @require
     - (void)dismiss;
    @end
    @interface ModalViewController
    

    In your presented controller, which is ModalViewController in your case, declare the following in .h:

    @property(assign, nonatomic) id<ModalViewControllerProtocol>myDelegate;
    

    and make your presenting controller so that it adopts to the protocol:

    @interface presentingViewController <ModalViewControllerProtocol>
    

    And:

    ModalViewController *modal = [[ModalViewController alloc] init];
    modal.myDelegate = self;
    [self presentViewController:modal animated:YES completion:nil];
    

    When your modal view controller is presented and you would like to tell your presenting controller to dismiss it, you could do:

    [self.myDelegate dismiss];
    

    And finally implement the dismiss method in your presenting view controller:

    - (void)dismiss
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    

    One could also forget about all of the aforementioned and simply call the following in the presented view controller (which, in your case, the ModalViewController):

    [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
    

    But there are cases that self.presentingViewController is not returning the same controller that presented the modal view controller. Hence, using the protocol method would assure that we would like the same presenting view controller to dismiss the presented controller.