How to hide Textbox Keyboard when "Done / Return" Button is pressed Xcode 4.2

IphoneIosxcode4.2

Iphone Problem Overview


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?

Iphone Solutions


Solution 1 - Iphone

Implement the delegate method UITextFieldDelegate, then:

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

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

Solution 2 - Iphone

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;
}

Solution 3 - Iphone

Make category on UIViewController with next method

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTalonView Question on Stackoverflow
Solution 1 - IphonePaul HunterView Answer on Stackoverflow
Solution 2 - IphoneHimanshu padiaView Answer on Stackoverflow
Solution 3 - IphoneixiView Answer on Stackoverflow