0

I have some UITextFields which bring the keyboard open.

My question is, how can I detect a touch on the screen that is NOT in ANY UITextField

Pseudocode of what I need:

if(screen is touched)
   if(touched view is NOT a UITextField)
      [self.view endEditing:YES];

Is there an easy way to accomplish this? Or another easier way to hide the keyboard when a UITextField is not touched?

Thanks!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
user1282637
  • 1,827
  • 5
  • 27
  • 56

2 Answers2

2

Just add UITapGestureRecognizer to your view and use [self.view endEditing:YES];

- (void)addTapGesutre {
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]  initWithTarget:self
                                                                             action:@selector(handleTapGesture:)];
    tapGesture.numberOfTapsRequired = 1;
    [self.view addGestureRecognizer:tapGesture];
}

- (void)handleTapGesture:(UITapGestureRecognizer *)tap {
    if (tap.state == UIGestureRecognizerStateEnded) {
        [self keyboardDismiss];
    }
}

- (void)keyboardDismiss {
    [self.view endEditing:YES];
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Ros
  • 144
  • 8
  • Thanks, this works, however it doesn't work for views that already detect taps (i.e. buttons). For those, I just added `[self keyboardDismiss]` to their IBActions. – user1282637 Sep 26 '15 at 20:34
0

You can actually use the touches began method.

Look at the documentation here.

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    view.endEditing(true)
}

From the documentation -

If you override this method without calling super (a common use pattern), you must also override the other methods for handling touch events, if only as stub (empty) implementations.

Pratik Patel
  • 439
  • 5
  • 15
  • FYI - the question is tagged Objective-C. Answers should be posted in the appropriate language. – rmaddy Sep 26 '15 at 20:42