Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Detect Touch outside a view
@property (nonatomic, strong) UITapGestureRecognizer *gesture;
//==========================================================================================
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
self.gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
self.gesture.numberOfTapsRequired = 1;
self.gesture.numberOfTouchesRequired = 1;
self.gesture.delegate = self;
[self.gesture setCancelsTouchesInView:NO];
[self.view.window addGestureRecognizer:self.gesture];
}
//==========================================================================================
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
CGPoint point = [touch locationInView:nil];
UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];
CGPoint pointInSubview = [self.view convertPoint:point fromView:mainWindow];
if (!CGRectContainsPoint(self.view.frame, pointInSubview)) {
[self close:self];
return NO;
}
return YES; // handle the touch
}
//==========================================================================================
- (void)handleTap:(UITapGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer.state != UIGestureRecognizerStateEnded) {
return;
}
// Handle the tap if you want to
}
//==========================================================================================
#pragma mark - Close modal
- (IBAction)close:(id)sender
{
self.gesture.delegate = nil;
[self.view.window removeGestureRecognizer:self.gesture];
[self dismissViewControllerAnimated:YES completion:^{
}];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment