Focus outside UITableView to remove keyboard

I use UITableView to control user login / password. Now this is the only control in the view, as well as the login button. When I click inside, the text editing content becomes active, the keyboard pops up and I can type. however, there is no way to stop editing. I would like to click on the white background of my UIView so that the focus is removed from the text editors inside my UITableVIew, and the keyboard becomes invisible again.

How to do it?

+3
source share
3 answers

In, viewDidLoadmake your viewing controller listen for keyboard notifications and create a tap recognizer that will receive all events outside of your tableView:

- (void)viewDidLoad
{
   [super viewDidLoad];
   ...

    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(dismissKeyboard:)];

    ... 
}

Then, in the notification methods for the keyboard, add and remove the gesture recognizer from your view.

//add gesture recognizer when keyboard appears
-(void)keyboardWillShow:(NSNotification *) note {
    [self.view addGestureRecognizer:tapRecognizer];
}

//remove it when keyboard disappears
-(void)keyboardWillHide:(NSNotification *) note
{
    [self.view removeGestureRecognizer:tapRecognizer];
}

In the action method of your gesture recognizer, you leave all the first responders to remove the keyboard:

-(IBAction)dismissKeyboard:(id)sender
{
    //this removes ALL firstResponder from view
    [self.view endEditing:TRUE];
}

Remember to end listening to keyboard notifications at some point:

[[NSNotificationCenter defaultCenter] removeObserver:self];
+3
source

You can add a button for which the alpha channel is zero. Your login and password field is located. Set the action on this button as follows:

-(void)hideKeyboard:(id)sender
{
   [self.username resignFirstResponder];
   [self.password resignFirstResponder];
}
+5
source

GestureRecognizer

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resignKeyBoard)];
[tap setNumberOfTapsRequired:1];
[self.view addGestureRecognizer:tap];
+1

All Articles