resign keyboard in UITextField

1.5k Views Asked by At

I'm working with storyboards on iOS 5 and have a simple screen that has a UITextField on it. I want to dismiss the keyboard when the user hits "Return". I followed other suggestions such as having my controller implements the UITextFieldDelegate protocol and implements textFieldShouldReturn: as follows:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [questionField resignFirstResponder];
    return YES;
}

However I see that this method is never called. I have set the controller of my view in storyboarding to my custom UIViewController.

I also tried a different implementation where I create an IBAction called dismissKeyboard but oddly I can't connect the Did Exit action to my UITextField.

Any ideas?

Update : So the problem seems to be that I'm using a UITextView and not a UITextField. I wanted a large area for the text to be entered. When I change the entry field to a UITextField it works fine. Any ideas on how to make it work with a UITextView?

3

There are 3 best solutions below

1
On

You should connect the dismiss method to the text field's Did End Editing action.

1
On

If you want the keyboard to dismiss when tap the return key for the textview use this delegate function,

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

    if([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }

    return YES;
}
0
On

So the solution to resign the keyboard for a UITextView is to implement shouldChangeTextInRange.