1

I have a UIViewController containing a UIScrollView that takes up the whole VC and within the UIScrollView various elements including a number of text fields.

I have a generic method for dismissing the keyboard where if you tap anywhere on the scrollview, the keyboard is dismissed as follows:

in viewdidload:

UITapGestureRecognizer *tapScroll = [[UITapGestureRecognizer alloc]initWithTarget:self 
action:@selector(tapped)];
    tapScroll.cancelsTouchesInView = NO;
    tapScroll.delegate = self;
    [self.scrollView addGestureRecognizer:tapScroll];

- (void) tapped
{
NSLog(@"tapped on scrollview");
    [self.view endEditing:YES];
}

The problem is that when you click on UITextField, a fair percentage of the time it triggers the tapped method because the click on the textfield also registers as tap on underlying scrollview. This keeps the keyboard from appearing so you can't enter anything into the keyboard. (I can prevent this behaviour by commenting out [self.view endEditing:YES]; in the tapped method).

Can anyone suggest a way to detect the textfield touches to show keyboard without causing scrollview to recognize tap, or alternatively dismiss keyboard only on touching blank part of the screen.

Thanks for any suggestions.

Mr.Kushwaha
  • 491
  • 5
  • 14
user6631314
  • 1,751
  • 1
  • 13
  • 44
  • Check other questions such as https://stackoverflow.com/questions/5222998/uigesturerecognizer-blocks-subview-for-handling-touch-events for info about handling gestures with subviews. – Stonz2 Nov 08 '17 at 16:23

1 Answers1

1

You can check what view the tap came from using something like this:

- (void)tapped:(UIGestureRecognizer *)gestureRecognizer{

   UIEvent *event = [[UIEvent alloc] init];
   CGPoint location = [gestureRecognizer locationInView:self.view];

   //Perform hit test
   UIView *view = [self.view hitTest:location withEvent:event];

   if ([view.gestureRecognizers containsObject:gestureRecognizer]) {

       //End Editing
       [self.view endEditing:YES];
   }

}
Neil Faulkner
  • 526
  • 1
  • 4
  • 22