Remove keyboard when table cell selected

1.5k views Asked by At

I have a modal set up like this:

enter image description here

Despite appearances, the first two fields are UITextFields that become first responders and display the keyboard. The third 'Department' item is a table view and pushes another view.

I have implemented a scroll view so that while either of the fields is being edited, the user can scroll around and reach the department cell:

enter image description here

When it is selected, before the push, I would like to hide the keyboard. It's a small detail, but try adding a new event on Apple's 'Calendar' app. It opens with the first text field as first responder (so keyboard is present). If you select the start/end cell, the keyboard hides as the next view is pushed.

How do I achieve this? As a test I tried:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"hiding keyboard");
if ([ingredientName isFirstResponder]) {
    NSLog(@"resigning name field");
    [ingredientName resignFirstResponder];
}
else if ([ingredientAmount isFirstResponder]){
    NSLog(@"resigning amount field");
    [ingredientAmount resignFirstResponder];
}

}

The logging confirms that these are getting called. But the keyboard does not hide. It simply stays in place as the view slides out. And on return, the previous field still has focus (and the keyboard is out).

Any ideas?

3

There are 3 answers

2
LJ Wilson On BEST ANSWER

Two things: Are you using a segue for pushing that other VC? If so, resign the keyboard in the prepareForSegue method.

If not, try using willSelectRowForIndexPath instead of didSelectRowAtIndexPath

3
jonkroll On

resignFrstResponder will not dismiss the keyboard when you're using a modal view.

Another dev found a workaround for this behavior here: http://viraj-workstuff.blogspot.com/2010/12/resignfirstresponder-does-not-hide.html

0
magma On

Not terribly elegant, but try stealing the firstresponder status with an ad-hoc, invisible UITextField:

-(void)dismissKeyboard {
    UITextField *textField;
    textField=[[UITextField alloc] initWithFrame:CGRectZero];
    [self.view addSubview:textField];
    [textField becomeFirstResponder];
    [textField resignFirstResponder];
    [textField removeFromSuperview];
    // [textField release] // uncomment if not using ARC
}