Search code examples
cocoa-touchuitextfielduikeyboarduitextfielddelegate

textFieldShouldEndEditing not called when user taps Done Button in UIKeyboard


I do validation of UITextField in textfieldShouldEndEditing delegate method, so every time I change the UITextfield being edited the method is called and the validation is performed.

The return button of the keyboard is configured as Done button. When it is pressed I process the input, but the textfieldShouldEndEditing of the last edited UItextField is never called before, so it is not validated.

This seems strange to me since the normal behavior is the user just hitting done button after entering the last character in the field, but this does not trigger the textFieldShouldEndEditingmethod.

To take on this I have to force validation again in the textfieldShouldReturn method.

Maybe I'm missing some point since I can't find the logic in this.


Solution

  • I have found the problem.

    I have to resignFirstResponder in textfieldShouldReturnand then the textfieldShouldEndEditingis called after.

    This are my methods. I have two UITextFields. self.usernameis an IBOutlet to one of them with return button configured as NEXT. self.passwordis other IBOutlet pointing to a UITextField with Done return Button.

    -(BOOL)textFieldShouldEndEditing:(UITextField *)textField
    {
        if (textField == self.userName) {
            return [self validateUserName:textField.text];
    
        }
    
    
    
        if (textField == self.password) {
            return [self validatePassword:textField.text];
    
        }
    
        //No hay errores de validación
        return YES;    
    }
    
    
    -(BOOL)textFieldShouldReturn:(UITextField *)textField
    {
        //In userName return is Next
        //In password return is Done
    
        if (textField == self.userName) {
            [self.password becomeFirstResponder];
        } 
        [textField resignFirstResponder];
        return YES;    
    }