How to dismiss keyboard iOS programmatically when pressing return

The simple way is to connect the delegate of UITextField to self (self.mytestField.delegate = self) and dismiss the keyboard in the method textFieldShouldReturn using [textField resignFirstResponder];

Another way to dismiss the keyboard is the following:

Objective-C

[self.view endEditing:YES];

Swift:

self.view.endEditing(true)

Put [self.view endEditing:YES]; where you would like to dismiss the keyboard (Button event, Touch event, etc.).


Add a delegate method of UITextField like this:

@interface MyController : UIViewController <UITextFieldDelegate>

And set your textField.delegate = self; then also add two delegate methods of UITextField

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{   
    return YES;
}

// It is important for you to hide the keyboard
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

simply use this in swift to dismiss keyboard:

UIApplication.sharedApplication().sendAction("resignFirstResponder", to:nil, from:nil, forEvent:nil)

Swift 3

UIApplication.shared.sendAction(#selector(UIResponder.resign‌​FirstResponder), to: nil, from: nil, for: nil)