Best method to save UITextField test: textFieldShouldReturn or textFieldDidEndEditing

后端 未结 1 1394
一向
一向 2021-01-06 06:54

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 m

相关标签:
1条回答
  • 2021-01-06 07:31

    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;
    }
    
    0 讨论(0)
提交回复
热议问题