Skip to content

Instantly share code, notes, and snippets.

@jhonsore
Last active February 9, 2016 21:10
Show Gist options
  • Save jhonsore/ffd6d0ea576f0ca2d4bb to your computer and use it in GitHub Desktop.
Save jhonsore/ffd6d0ea576f0ca2d4bb to your computer and use it in GitHub Desktop.
Dismiss keyboard in IOS
//Add UITextFieldDelegate in Controller
@interface ViewController : UIViewController<UITextFieldDelegate>
UITapGestureRecognizer *tapRecognizer;
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(keyboardWillShow:) name:
UIKeyboardWillShowNotification object:nil];
[nc addObserver:self selector:@selector(keyboardWillHide:) name:
UIKeyboardWillHideNotification object:nil];
tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(didTapAnywhere:)];
//Add delegate to all fields to dismiss keyboard when return button is pressed in keyboard
field.delegate = self;
-(void) keyboardWillShow:(NSNotification *) note {
[self.view addGestureRecognizer:tapRecognizer];
}
-(void) keyboardWillHide:(NSNotification *) note
{
[self.view removeGestureRecognizer:tapRecognizer];
}
-(void)didTapAnywhere: (UITapGestureRecognizer*) recognizer {
[self.view endEditing:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment