Archive for March, 2010

iPhone: Moving Content Located Under The Keyboard

Here’s what I have learned recently about trying to support editing in an iPhone app.

In developing an iPhone app that supports editing text, it doesn’t take long before you have to deal with the problem of the keyboard displaying on top of the text field or text view that you want to edit. I was surprised at how long it took me to come up with a solution.

I started with the iPhone Application Development Guide and looked in Chapter 5 on “Text and Web”. There is a section there titled “Moving Content That Is Located Under The Keyboard”. The guidance there is good, but what was lacking was a complete example that I could download and reverse engineer. As a new person to iPhone development, I find it still is easy to misinterpret explanations. I searched and searched but could not find anything on the web where someone posted a working example. So here’s mine.

Zip file: Under Keyboard project. This code works with Xcode 3.1.3. The views are done using Interface Builder.

Here are a few screen captures to show what the app looks like as you edit. Figure 1 is a screenshot of the app as it starts. The text field and text view have been placed low deliberately to illustrate how to scroll the view up as the keyboard appears.

Figure 1

Figure 2 shows what the screen looks like as you begin to edit the name in the text field. Notice that the everything has scrolled up enough to allow you to see the text field as you edit.

Figure 2

If you click either button or the return button, the keyboard goes away and the view scrolls back to its original position.

The same behavior holds for the text view, which is show in Figure 3. The only difference when editing in the text view is that you have to click the done button to stop editing in the view.

Figure 3

This took quite awhile to figure out. The trickiest thing for me was figuring out what to do in Interface Builder since most of the examples I found that explained scrolling well assumed you were creating the views by hand.



Follow

Get every new post delivered to your Inbox.

Join 73 other followers