56

I created a Text Field in Interface Builder. I set it's "Return Key" to Done. This is a one line only input (so it wont need multiple lines).

How do I hide the virtual keyboard when the user taps the done button?

Talon
  • 4,937
  • 10
  • 43
  • 57

3 Answers3

155

Implement the delegate method UITextFieldDelegate, then:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.yourIBtextField.delegate = self;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return NO;
}
Damia Fuentes
  • 5,308
  • 6
  • 33
  • 65
Paul Hunter
  • 4,453
  • 3
  • 25
  • 31
  • 17
    The part that I was missing was adding to the interface in the *.h file. Once I added that, this code worked without issue. Hope that helps someone else out! – proudgeekdad Mar 27 '13 at 03:06
  • 7
    In this situation is required. – brooNo Sep 02 '13 at 16:27
  • 3
    You can also connect the delegate from the storyboard (xib), if you drag connection from the textField to the viewController representation. That way you don't have to write the line from viewDidLoad method. – lgdev Nov 05 '13 at 14:20
9

UITextView does not have any methods which will be called when the user hits the return key.

Even then if you want to do this, implement the textView:shouldChangeTextInRange:replacementText: method of UITextViewDelegate and in that check if the replacement text is \n, hide the keyboard.

There might be other ways but I am not aware of any.

Make sure you declare support for the UITextViewDelegate protocol.

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

    if([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Himanshu padia
  • 7,428
  • 1
  • 47
  • 45
1

Make category on UIViewController with next method

- (void)hideKeyboard
{
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder)
                                               to:nil
                                             from:nil
                                         forEvent:nil];
}
ixi
  • 59
  • 5