I’m making a partial overlay modal in my app with the code from “Semi-Modal (Transparent) Dialogs on the iPhone” at ramin.firoozye.com. In doing so, the button that calls the modal is still visible and clickable. I will hide this button when the modal spawns, but I want to be sure if the user clicks very quickly twice, a new modal doesn’t come up for each click. What is the best way to check that the modal doesn’t already exist when calling it from the button click?
You can download the test project here. For those that don’t have xcode, the relevant functions are below:
I call forth the modal on button click with this:
- (IBAction)displayModal:(id)sender {
ModalViewController *modalController = [[ModalViewController alloc] initWithNibName:@"ModalViewController" bundle:nil];
modalController.view.frame = CGRectOffset(modalController.view.frame, 0, 230);
[self showModal:modalController.view];
}
Then use this function to animate the custom modal over the current view:
- (void)showModal:(UIView*) modalView {
UIWindow* mainWindow = (((TestAppDelegate*) [UIApplication sharedApplication].delegate).window);
CGPoint middleCenter = modalView.center;
CGSize offSize = [UIScreen mainScreen].bounds.size;
CGPoint offScreenCenter = CGPointMake(offSize.width / 2.0, offSize.height * 1.5);
modalView.center = offScreenCenter; // we start off-screen
[mainWindow addSubview:modalView];
// Show it with a transition effect
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.4]; // animation duration in seconds
modalView.center = middleCenter;
[UIView commitAnimations];
}
Then I dismiss the modal on button click with this:
- (IBAction)dismissModal:(id)sender {
[self hideModal:self.view];
}
And then use these functions to animate the modal offscreen and clean itself up:
- (void)hideModal:(UIView*) modalView {
CGSize offSize = [UIScreen mainScreen].bounds.size;
CGPoint offScreenCenter = CGPointMake(offSize.width / 2.0, offSize.height * 1.5);
[UIView beginAnimations:nil context:modalView];
[UIView setAnimationDuration:0.7];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(hideModalEnded:finished:context:)];
modalView.center = offScreenCenter;
[UIView commitAnimations];
}
- (void)hideModalEnded:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
UIView* modalView = (UIView *)context;
[modalView removeFromSuperview];
[self release];
}
Any help is greatly appreciated!
I really didn’t want to resort to a global variable to keep track of the modal already existing, so I decided to use notification.
I put this in my navigation controller where I call the modal:
Then I put this in the modal controller where the modal is dismissed:
I could probably do it with the AppDelegate as well. If anyone thinks that, or anything else, would be a better fit for this, let me know.