12

How to hide the keyboard programmatically in iphone?

Cœur
  • 32,421
  • 21
  • 173
  • 232
thndrkiss
  • 4,229
  • 6
  • 52
  • 92

6 Answers6

22

Tell the UIResponder subclass that is currently first responder to resign its first responder status:

[responder resignFirstResponder];
glorifiedHacker
  • 6,390
  • 2
  • 20
  • 26
20
[textFieldName resignFirstResponder];
Sam Jarman
  • 7,025
  • 14
  • 49
  • 98
4

It's easy:

ObjC

[[[UIApplication sharedApplication] keyWindow] endEditing:YES];

Swift

UIApplication.shared.keyWindow?.endEditing(true)

take a look at UIView Class Reference for endEditing. Causes the view (or one of its embedded text fields) to resign the first responder status. And keyWindow is the only window that receives keyboard events, so this solution is guarantied to always work.

Community
  • 1
  • 1
leviathan
  • 10,700
  • 5
  • 39
  • 39
2

Call this in your ViewController

[self.view endEditing:YES];
Philip J. Fry
  • 1,175
  • 1
  • 8
  • 10
0

If you are using textview then

- (BOOL)textView:(UITextView *)textView
 shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text
{
  if ([text isEqualToString:@"\n"])
 {
    [textView resignFirstResponder];
    [self keyboardWillHide];
 }
}

and if you are using textfield then

-(BOOL)textFieldShouldReturn:(UITextField*)textField;
 {

[textField resignFirstResponder];

 }
Laur Ivan
  • 3,877
  • 3
  • 33
  • 61
iKambad
  • 333
  • 2
  • 13
0

Here is the swift version:

UIApplication.sharedApplication().sendAction("resignFirstResponder", to:nil, from:nil, forEvent:nil)
Cœur
  • 32,421
  • 21
  • 173
  • 232
Chathuranga Silva
  • 6,275
  • 2
  • 43
  • 51