iOS - Dismiss keyboard when touching outside of UITextField iOS - Dismiss keyboard when touching outside of UITextField ios ios

iOS - Dismiss keyboard when touching outside of UITextField


You'll need to add an UITapGestureRecogniser and assign it to the view, and then call resign first responder on the UITextField on it's selector.

The code:

In viewDidLoad

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];[self.view addGestureRecognizer:tap];

In dismissKeyboard:

-(void)dismissKeyboard {    [aTextField resignFirstResponder];}

(Where aTextField is the textfield that is responsible for the keyboard)

Swift 3 version looks like that

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard (_:)))self.view.addGestureRecognizer(tapGesture)

For dismissKeyboard

@objc func dismissKeyboard (_ sender: UITapGestureRecognizer) {    aTextField.resignFirstResponder()}


I mashed up a few answers.

Use an ivar that gets initialized during viewDidLoad:

UIGestureRecognizer *tapper;- (void)viewDidLoad{    [super viewDidLoad];    tapper = [[UITapGestureRecognizer alloc]                initWithTarget:self action:@selector(handleSingleTap:)];    tapper.cancelsTouchesInView = NO;    [self.view addGestureRecognizer:tapper];}

Dismiss what ever is currently editing:

- (void)handleSingleTap:(UITapGestureRecognizer *) sender{    [self.view endEditing:YES];}


Check this, this would be the easiest way to do that,

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{      [self.view endEditing:YES];// this will do the trick}

Or

This library will handle including scrollbar auto scrolling, tap space to hide the keyboard, etc...

https://github.com/michaeltyson/TPKeyboardAvoiding