0

I have seen many samples on how to hide the keyboard when pressing return or actioning some button.

But my case is different: How do I dismiss the keyboard just clicking outside the TextField? Imagine the user has tapped a TextField to enter some text... But he regrets and just want to hide the keyboard and continue viewing the screen as before tapping in the textfield

I don't find how to do it

Thanks in advance

Pedro

Filip Radelic
  • 26,607
  • 8
  • 71
  • 97
ElPiter
  • 4,046
  • 9
  • 51
  • 80

3 Answers3

1

Implement touchesBegan and resign the text field as first responder.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [activeTextField resignFirstResponder];
}

If you have multiple text fields, you should store a pointer to currently active one in activeTextField instance variable. To do that, you would have to set self as delegate for all text fields and implement this delegate method:

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    activeTextField = textField;
}
Filip Radelic
  • 26,607
  • 8
  • 71
  • 97
1

Try this code.

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent*)event 
{
 UITouch *touch = [touches anyObject];
 if([touch view] == self.view)
    [textField resignFirstResponder];
}
Shrey
  • 1,959
  • 2
  • 21
  • 44
  • 1
    There's really no reason to check `if([touch view] == self.view)` here because he would want all the touches outside of the text field to dismiss the keyboard, and this method will not be called if the user touched text field (or other element that handles touch itself). – Filip Radelic Aug 07 '11 at 14:34
0

You can rasignfirstresponder on touch up outside event.
Otherwise have a look at this answer
iphone, dismiss keyboard when touching outside of UITextField

Community
  • 1
  • 1
pasine
  • 11,311
  • 10
  • 49
  • 81
  • This will not work because the text field will not receive touch events unless they originate from _inside_ the text field. Otherwise some other view will get the touch event. Touch up outside is when you start to press a button then you cancel by dragging your finger off of it. – Alex Gosselin Aug 07 '11 at 15:10