Feb 04

Hiding the Keyboard when touching background

If you are working on an iOS app and have the need for the user the enter input then you usually use a textfield or textview. I was working on a login screen and had a very annoying experience where the keyboard wouldn’t go away after I had finished entering my text. What was especially annoying was that I had encountered it before and had simply forgotten how to resolve it. So I’m writing this up for myself or anyone else who needs the info.

All you have to do is make sure that your view has ‘User Interaction Enabled’ checked under the ‘Attributes Inspector’. Then add the following block of code to your view’s implementation. You can see that I have two textFields called txtUsername and txtPassword. You’ll want to change them to match the names of all the text fields on your form (you don’t know which one is actually the first responder at the time, but from what I’ve read it doesn’t hurt to resign if you are not it anyway). So that’s it.

– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

UITouch * touch = [touches anyObject];

if(touch.phase == UITouchPhaseBegan) {

[self.txtPassword resignFirstResponder];

[self.txtUserName resignFirstResponder];

}

}

Here’s another place that discusses it in a bit more detail.

I’ll also mention that some people use a hidden button the size of the view. Then they tie that button to a “hideKeyboard” method. That solution is also discussed in that thread. I found a better explanation of it a Sams Publishing teach yourself Iphone Development book, but the discussion on that thread will suffice. For my own reference it is on page 179-182. It also discusses how to release the keyboard when the “Done” button is pressed. You will probably want to implement BOTH.