Tuesday, October 4, 2016

Hide Keyboard tap on screen iOS

The easiest way to hide iOS keyboard by touching or tapping on screen
is TapGesture. There are many other ways to do this. But I find really easy to use this GestureRecognizer.

First question why do we need to implement this critical Gesture thing in the project? We could easily use the UITextView delegate method to do it. Right!! But if your client wants to jump to a new line in the input text. That means if user wants to use the return button for breaking the line. In that case you need to add other functionalities which will hide the keyboard. Let's see how to implement this TapGestureRecognizer.

First of all in viewDidLoad add the snippet given below
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard:)];
[self.view addGestureRecognizer:tapGesture];

Then write down method for  hideKeyboard 
-(void)hideKeyboard:(id)sender {
    [self.textView resignFirstResponder]; /// self.textView is name of your UITextView
}

Second question, if we have multiple UITextView for same situation (return key will act as new line) in our project? Because above snippet will work only for a single UITextView. To handle multiple UITextView just replace above snippet with below
-(void)hideKeyboard:(id)sender {
    if(![sender isKindOfClass:[UITextView class]]){
         NSLog(@"in the uiview class");
         [[self view] endEditing:YES]; /// This will work for both cases. Multiple or single UITextView
    }
}

Hopefully this tutorial will help you.

No comments:

Post a Comment