Best method to save UITextField test: textFieldSho

2020-03-04 02:29发布

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!!

标签: ios
1条回答
▲ chillily
2楼-- · 2020-03-04 03:23

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;
}
查看更多
登录 后发表回答