Monday, April 26, 2010

How to Get Rid of Keyboard with a Tap on Background

There is a screen with a couple of UITextFields and UIButtons. When user taps on UITextField, keyboard popups. Very nice of iPhone SDK to provide such a feature! Each UITextField and UIButton is a clickable object with easy callbacks.

But how do you get rid of keyboard?

Should you have a special "Please hide keyboard" button or tap into accelerometer to notice when user gets desperate enough to start shaking the device? There's an easier way...

Add a full-screen empty non-editable UITextView over the whole screen. Select each clickable object e.g. UITextField, UIButton or other UITextViews and use Interface Builder menu item Layout - Send to Front to place them on top of your full-screen UITextField.

When user clicks on anywhere except your clickable objects, keyboard disappears. What a relief!

Please note that, if you leave any non-clickable objects e.g. UILabel on top of your full-screen UITextView, clicking on those spots will not hide keyboard.

3 comments:

  1. Hmph, seems to have stopped working with iOS4.x! Got to do long touch now, which pops up copy bubble and closes keyboard at the same time.

    Got to think of another way...

    ReplyDelete
  2. Thanks for sharing, How do you make the UITextView the size of the view?

    ReplyDelete
  3. You define the size of this magical UITextView same as the size of the view, where it's inside. Very easy with interface builder. Anyway it stopped working, so I replaced it with UIButton (I recall). Same general idea...

    ReplyDelete