1

My iPhone App has a numerical text-field (and some other controls). A num pad is shown when the user taps the text field. I like to dismiss this num pad (by [self.textField resignFirstResponder]) as soon as the user taps on the view's background (easy to detect) but also when the user taps on any other control!

How can I detect that the user taps outside the text field (but not necessarily on the background)?

ragnarius
  • 5,642
  • 10
  • 47
  • 68

3 Answers3

3

I always do this in viewDidLoad:

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
[self.view addGestureRecognizer:tap];

and then implement:

- (void)dismissKeyboard
{
   [self.view endEditing:YES];
}

Works like a charm :)

nburk
  • 22,409
  • 18
  • 87
  • 132
  • Thanks, it works semi-good. It works when the user touches a slider, but not when he/she touches a segmented-control. – ragnarius Jul 31 '14 at 15:28
  • add `[self dismissKeyboard]` in the first line of your action method for your segmented control and it'll work. – nburk Aug 01 '14 at 16:12
1

Just use:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
   [self.view endEditing:YES];
}
Rafał Sroka
  • 39,540
  • 23
  • 113
  • 143
1

Extending on @reecon's answer about touchesBegan. I wouldn't recommend to use it as you'd end up with a jumping keyboard up and down when the user taps repeatedly and believe me, it looks totally weird (at least it was on iOS 7.1.1 in one of my projects).

I'd go for the good old full screen UITapGestureRecognizer. You could also use a full screen UISwipeGestureRecognizer with a down direction - it would look and feel even cooler, as if the user is sliding down a keyboard.

Both gestures are added through the IB and require no code to set up.

Tapping on "other controls" is a totally different story though and you'd have to do it all by hand - no gestures can help you.

Sergey Grischyov
  • 11,995
  • 20
  • 81
  • 120