Skip to content

Instantly share code, notes, and snippets.

@sburlot
Created March 22, 2015 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sburlot/9856a15119985a6f1a87 to your computer and use it in GitHub Desktop.
Save sburlot/9856a15119985a6f1a87 to your computer and use it in GitHub Desktop.
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