Lior Pollak Lior Pollak - 4 years ago 179
iOS Question

Understanding resignFirstResponder with UITextField

I'm trying to get rid of the keyboard when the user touch outside my UITextField, by using this method:

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


However, this seems to call a method that is called after pressing the return button on the keyboard, but I just want the keyboard to vanish, not to press return for me.
How can I accomplish that?

Thanks!

EDIT: tGilani's answer is the most straight-forward way, works like a charm, without changing to UIControl. But I guess jonkroll's answer also works.

Answer Source

try

[self.view endEditing:YES];

Update:

Take a boolean value and set it to false in init method. In your textFieldShouldReturn delegate method method, execute the code if it is false, skip otherwise

- (BOOL) textFieldShouldReturn:(UITextField*)textField
{
    if (!boolean)
    {
        // YOur code logic here
    }
    boolean = false;
}

in your method where you call the endEditing method, set boolean to true.

boolean = YES;      
[self.view endEditing:YES];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download