Search code examples
iphoneiosuitextfielduiactionsheetuitextfielddelegate

Dismiss the keyboard if action sheet is going to popup


I have a UIDatePickerView inside UIActionSheet as a input to the UITextField. When focusing on UITextField UIActionSheet will popup instead of Keyboard. When clicking on the done button in the UIActionSheet it'll hide. I have several other text fields behave as normal (Showing keyboard).

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if ([textField isEqual:txtExpDate]) {
        [textField resignFirstResponder];
        [self showDatePicker];
    }
}


- (void) showDatePicker{
    UIActionSheet *datePickerActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"Done" otherButtonTitles:nil];
    datePickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 80, 0, 0)];
    datePickerView.datePickerMode = UIDatePickerModeDate;
   [datePickerActionSheet addSubview:datePickerView];
   [datePickerActionSheet showInView:self.navigationController.view];
   [datePickerActionSheet setBounds:CGRectMake(0, 0, 320, 500)];
   [datePickerActionSheet release];

}

Now my problem is, Let say first user taps on normal textfield. Which will popups keyboard. Then without selecting done button he taps on date field. Which will popup action sheet (without dismissing the keyboard). After hiding actionsheet user has to tap on other text filed and click on return key of the keyboard.

I want to hide the keyboard if action sheet is going to popup?


Solution

  • Make the text field resignFirstResponder when you are going to bring up the action sheet. If you have more than one text fields, create an instance variable of type UITextField in .h file.

    UITextField *currentTextField;
    

    Then you can keep reference of the current text field in textFieldDidBeginEditing: method.

    - (void)textFieldDidBeginEditing:(UITextField *)textField {
    
        currentTextField = textField;
        ....
    

    And, call [currentTextField resignFirstResponder] in showDatePicker method.

    - (void)showDatePicker {
    
        [currentTextField resignFirstResponder];
        UIActionSheet *datePickerActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"Done" otherButtonTitles:nil];
        ...
    

    EDIT: @Samuel Goodwin is correct. We don't have to track the text fields. We can simply do the following to dismiss the keyboard.

    - (void)showDatePicker {
    
        [self.view endEditing:YES];
        ...