Reputation: 4324
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
Upvotes: 0
Views: 636
Reputation: 1977
Try this code.
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent*)event
{
UITouch *touch = [touches anyObject];
if([touch view] == self.view)
[textField resignFirstResponder];
}
Upvotes: 1
Reputation: 26683
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;
}
Upvotes: 1
Reputation: 11563
You can rasignfirstresponder on touch up outside event.
Otherwise have a look at this answer
iphone, dismiss keyboard when touching outside of UITextField
Upvotes: 0