Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best method to save UITextField test: textFieldShouldReturn or textFieldDidEndEditing

Tags:

ios

my objective simply to save text on UITextField after user click done button on keyboard. I could either do this in extFieldShouldReturn or textFieldDidEndEditing: does it make any difference ? or there a better approach ?

Thanks!!

like image 666
user836026 Avatar asked Dec 02 '22 23:12

user836026


1 Answers

textFieldShouldReturn is only called if the user presses the return key. If the keyboard is dismissed due to some other reason such as the user selecting another field, or switching views to another screen, it won't be but textFieldDidEndEditing will be.

The best approach is to use textFieldShouldReturn to resign the responder (hide the keyboard) like this:

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //hide the keyboard
    [textField resignFirstResponder];

    //return NO or YES, it doesn't matter
    return YES;
}

When the keyboard closes, textFieldDidEndEditing will be called. You can then use textFieldDidEndEditing to do something with the text:

- (BOOL)textFieldDidEndEditing:(UITextField *)textField
{
    //do something with the text
}

But if you actually want to perform the action only when the user explicitly presses the "go" or "send" or "search" (or whatever) button on the keyboard, then you should put that handler in the textFieldShouldReturn method instead, like this:

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //hide the keyboard
    [textField resignFirstResponder];

    //submit my form
    [self submitFormActionOrWhatever];

    //return NO or YES, it doesn't matter
    return YES;
}
like image 148
Nick Lockwood Avatar answered May 22 '23 03:05

Nick Lockwood