Adjusting a UIView to an appearing Keyboard

Just a quick tip I found out to make better use of space in my iPhone app. Consider the following situation: You have a Highscore View with a couple of stats of the game you just finished. Naturally you would like the user to be able to enter his nickname.

The problem

The input box is so far down in the view that it gets covered by the keyboard as soon as its activated. Now the user can enter his nickname but he can not see what he is typing. That is just not acceptable.

The solution

The naive solution would be to move the input field up so that the keyboard won’t block it. But that is unsatisfying. There must be a better solution… and there is: Just register for the Keyboard notifications and move the View up exactly as much as the keyboards height.

Step 1: Register for the appropriate notifications. Specifically the UIKeyboardWillShowNotification and the UIKeyboardWillHideNotification. Using the following commands the method -(void)keyboardWillShow will be executed when the keyboard appears and the method -(void)keyboardWillHide will be executed when the keyboard disappears.

Step 2: Implement the methods you just registered with the Notification Center. One method moves the view out of the way and the other moves it back into place. Quite simple when know it. -(void)keyboardWillShow moves the view 160px upwards. In my case that looked nice. Maybe you need to change that value to suit your needs.

Step 3: Tidy things up. At some point you really should remove your listener from the notification center. Otherwise, from that point on, your listener will be called for every keyboard that appears and most likely your listener will not be around for that… which ends badly.

The Result

Upon activating the input field the view moves smoothly out of the way and when you press “Done” the view moves back to where it was before.

Possible Problems

Currently the time for the keyboard to show is 0.3 seconds, but Apple may change that at any time. This is also true for the keyboard size. The default keyboard in portait mode is 216px in height and in landscape it is 162px, but that may also change at any time. If (for any reason) you need to find out the keyboard size you can do that pretty easily.

If you enjoyed this post, how about leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">