iPhone: UITextField End Editing event doesn't hide keyboard

AlienMonkeyCoder picture AlienMonkeyCoder · Feb 28, 2012 · Viewed 32.5k times · Source

I want to hide keyboard on UITextField end editing event but somehow I am not able to get following code working! When I press Done button, it hides the keyboard but not when I don't press done button and move to another UITextField where I don't need keyboard but UIPickerView. Basically UIPickerView is appearing but behind the keyboard. I am resigning current UITextField on end editing event as well as on begin editing for required text fields. The begin editing code works fine if I don't have keyboard already shown for previous UITextField. Could someone please tell me what am I doing wrong?

Following sequence works:

  1. Select normal UITextField and insert text, press done button (this hides keyboard)
  2. Select picker UITextField (this displays picker view)

..but following doesn't:

  1. Select normal UITextField and insert text
  2. Select picker UITextField (the picker view is behind the keyboard as I didn't press done button for previous UITextField). Here it calls end editing but it doesn't hide keyboard!

    - (BOOL)textFieldShouldReturn:(UITextField *)textField {
        [textField resignFirstResponder];
        scrollView.contentSize = CGSizeMake(320, 750);
        [scrollView setFrame:CGRectMake(0, 0, 320, 480)];
        return YES;
     }
    
    -(void)textFieldDidEndEditing:(UITextField *)textField  
    {
        [textField resignFirstResponder];
    }
    
    - (void)textFieldDidBeginEditing:(UITextField *)textField {
        DatePicker.hidden = YES;
        CountryPickerView.hidden = YES;
    
        switch (textField.tag) {
            case 3:
                [textField resignFirstResponder];
                DatePicker.hidden = NO;
                return;
            case 6:
                [textField resignFirstResponder];
                CountryPickerView.hidden = NO;
                return;
            default:
                break;
        }
        scrollView.contentSize = CGSizeMake(320, 650);
        [scrollView setFrame:CGRectMake(0, 0, 320, 260)];
    }
    

Answer

valexa picture valexa · Feb 28, 2012

You should not be relying on tags but pointers to the objects and remove [textField resignFirstResponder]; from textFieldDidEndEditing.

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField 
{ 
    if (textField == theTextFieldIDontWantKeyboardFor) {  
        [thepreviousTextField resignFirstResponder]; 
        return NO;
    }
    return YES; 
}