I have a UITextfield that i\'d like to dismiss the keyboard for. I can\'t seem to make the keyboard go away no matter what code i use.
To resign any text field in the app
UIApplication.shared.keyWindow?.endEditing(true)
This approach is clean and guarantied to work because the keyWindow is, by definition, the root view of all possible views displaying a keyboard (source):
The key window receives keyboard and other non-touch related events. Only one window at a time may be the key window.
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
// your code
[textField reloadInputViews];
}
In your view controller YourViewController.h file, make sure you implement UITextFieldDelegate protocol :
@interface YourViewController : <UITextFieldDelegate>
@end
Then, in YourViewController.m file, implement the following instance method:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.yourTextField1 resignFirstResponder];
[self.yourTextField2 resignFirstResponder];
...
[self.yourTextFieldn resignFirstResponder];
}
as a last resort
[myTextField resignFirstResponder]
Here, second paragraph in the Showing and Hiding the Keyboard section.
You just replace yourTextFieldName
with, you guessed it! your textfield. This will close the keyboard.
[yourTextFieldName resignFirstResponder];