views:

135

answers:

2

Is there a way to call code when a modal view is finished dismissing?

EDIT:

I'm sorry, I didn't clarify earlier. I'm trying to dismiss a UIImagePickerController and then show a MFMailComposeViewController and attach the image data to the email. When I try to call

[self presentModalViewController: mailController]

right after

[self dismissModalViewController];

I get errors and such.

A: 

You have to dismiss the modalViewController somehow right? Either a UIButton, or by code:

- (void)dismissModalViewControllerAnimated:(BOOL)animated

In the IBAction (e.g. delegate) for the UIButton or in the method above, call whatever code you want.

Jordan
You're saying to override `- (void)dismissModalViewControllerAnimated:(BOOL)animated`? I don't think that would work, see my edit.
Moshe
+2  A: 

You use a delegate pattern for the modal view to inform whoever presented it when it's finished.

MyModalViewController.h:

@protocol MyModalViewControllerDelegate;

@interface MyModalViewController : UIViewController
{
    id<MyModalViewControllerDelegate> delegate;
}

@property (nonatomic, assign) id<MyModalViewControllerDelegate> delegate;

@end


@protocol MyModalViewControllerDelegate
- (void)myModalViewControllerFinished:(MyModalViewController*)myModalViewController;
@end

MyModalViewController.m:

@synthesize delegate;

// Call this method when the modal view is finished
- (void)dismissSelf
{
    [delegate myModalViewControllerFinished:self];
}

ParentViewController.h:

#import "MyModalViewController.h"

@interface ParentViewController : UIViewController <MyModalViewControllerDelegate>
{
}

ParentViewController.m:

- (void)presentMyModalViewController
{
    MyModalViewController* myModalViewController = [[MyModalViewController alloc] initWithNibName:@"MyModalView" bundle:nil];
    myModalViewController.delegate = self;
    [self presentModalViewController:myModalViewController animated:YES];
    [myModalViewController release];
}

- (void)myModalViewControllerFinished:(MyModalViewController*)myModalViewController
{
    [self dismissModalViewControllerAnimated:YES];
}

EDIT:

I haven't used UIImagePickerController, but looking at the docs, it looks like you already have most of the code done for you, as there is an existing UIImagePickerControllerDelegate class that has three different "dismissal" delegate callbacks (although one is deprecated). So you should make your ParentViewController class (whatever that is) implement the UIImagePickerControllerDelegate pattern and then implement those methods. While each method will do something different (since you have to handle when the user actually selects an image, or if they cancel), they each will do the same thing at the end: call dismissModalViewControllerAnimated: to dismiss the picker.

Shaggy Frog
Can I use the delegate pattern with custom delegates on a UIImagePickerController?
Moshe