Trying to implement a UITapGestureRecognizer to a form sheet modal viewcontroller.
If user touches outside of the form sheet, form sheet should dismiss, it does so code works just fine.
Problem is If I manually dismiss the form sheet and try to touch any point in view it still tries to call UITapGestureRecognizer method and app crashes.
Error ::
-[xxxxView handleTapBehind:]: message sent to deallocated instance
-(void)done
{
[self.navigationController popViewControllerAnimated:YES];
//send notification that folder has been created
[[NSNotificationCenter defaultCenter] postNotificationName:@"refreshDetails" object:nil];
}
-(void)viewDidAppear:(BOOL)animated
{
// gesture recognizer to cancel screen
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapBehind:)];
[recognizer setNumberOfTapsRequired:1];
recognizer.cancelsTouchesInView = NO; //So the user can still interact with controls in the modal view
[self.view.window addGestureRecognizer:recognizer];
}
- (void)handleTapBehind:(UITapGestureRecognizer *)sender
{
if (sender.state == UIGestureRecognizerStateEnded)
{
CGPoint location = [sender locationInView:nil]; //Passing nil gives us coordinates in the window
//Then we convert the tap's location into the local view's coordinate system, and test to see if it's in or outside. If outside, dismiss the view.
if (![self.view pointInside:[self.view convertPoint:location fromView:self.view.window] withEvent:nil])
{
// Remove the recognizer first so it's view.window is valid.
[self.view.window removeGestureRecognizer:sender];
[self dismissModalViewControllerAnimated:YES];
}
}
}
Why is handleTapBehind: still called after I dismiss viewcontroller? How can I fix this?
You add gesture recognizer to window:
And set target to your controller;
So, when your controller closed – it’s released, but gesture recognizer still alive. And when it fire it try to send action to your controller, which already does not exists.
So, you should add recognizer to controller’s view or remove him in viewWillDissaper method.