Tag Archives: keyboard

Dismissing the keyboard

I dragged a UITextField onto my xib file, and hooked up the “Editing did end” action to my view controller, and put some code in there. When I ran it, touching in the text field brings up a keyboard… but the keyboard does nothing, and pressing return does not dismiss it.

The solution is straightforward, but not obvious. You need to set up a delegate which follows the UITextFieldDelegate protocol, and add the following method to it:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange: 
            (NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@"n"]) {
        [textField resignFirstResponder];
        return NO;
    }
    return YES;
}

Note if you are adding a UITextView though, the process is a little more subtle. First up, you probably want to allow carriage returns in the text, so you need to hook up a Done button somewhere else which resigns the first responder. You also need to set yourself up as a delegate for the UITextView, and then implement:

# pragma mark - UITextViewDelegate notifications

- (void)textViewDidBeginEditing:(UITextView *)textView {
    self.activeView = textView;
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    self.activeView = nil;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range 
                replacementText:(NSString *)text {
    // do anything you need, e.g. resize in response to a return key
    return YES;
}

Also, it’s recommended you do this inside a UIScrollView so you can scroll the field out from under the keyboard if needed – see Apple’s docs for more.