Sunday, January 25, 2009

Dismissing the Virtual Keyboard on iPhone

This post is a quick recipe for making the virtual keyboard go away on the iPhone SDK. There are two aspects to the problem: dismissing the keyboard when the user taps Done (easy, most resources describe this right) and dismissing the keyboard when the user taps the screen outside any control that can receive focus.

When the user taps Done
Go to Interface Builder, and connect the edit control's delegate outlet to your view controller (in most cases, that will be the File's Owner). If your delegate is different, follow the steps below making changes when appropriate.

In the view controller, use the following snippet:


That's it, you're done. Run the code in the simulator and confirm it works.

When the user taps outside the field
You might see some more complicated solutions elsewhere (like Apress' book). The solution below works without any UI changes. Add the snippet below in your view controller. The snippet belongs in the view's controller, even if your text field's delegate is another object.


Bonus: reacting to the user leaving the field
If you want to take an action when the user leaves a field (such as issuing a Web service request in the background), the approach below plays nice with the modifications described in this post:


This code belongs in the text field's delegate (most of the time, it is your view controller).

I hope this post makes your life a bit easier. Happy coding!

14 comments:

  1. life did just get very easy indeed!
    of all the solutions i've come across, this one (touchesEnded in particular) was the best for me.
    thanks for posting :D

    ReplyDelete
  2. Great post! Tapping outside of the field was exactly what I was looking for (number pad doesn't have a "done" key).

    Pure genius...almost TOO easy to implement...haha

    ReplyDelete
  3. that touchesEnded thing just rocked my socks.

    ReplyDelete
  4. I have been trying to do this for weeks. THANKS FOR THE HELP!

    ReplyDelete
  5. Wow - this was easy as pie.

    ReplyDelete
  6. You saved my bacon! Right to the point.

    ReplyDelete
  7. @Anonymous: thank you very much for letting me know, and sorry!

    The new template killed my embedded JavaScript. I reverted to the old template.

    ReplyDelete
  8. This was soo helpful! its so clear and to the point! touchesEnded is just beautiful!

    ReplyDelete
  9. I have been trying to do this since I bought my iPhone. This is very helpful. I appreciate it man! Thanks for sharing.

    keypads

    ReplyDelete
  10. Replies
    1. Thanks for letting me know! It seems like Pastie's JS serving is busted, so I added a link to the snippet in the post. I hope this will work for you!

      Delete