Created
March 22, 2015 23:54
-
-
Save sburlot/9856a15119985a6f1a87 to your computer and use it in GitHub Desktop.
Detect Touch outside a view
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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