Solution to the iOS software keyboard cover part of the UI

Problem 1

Often in develop iOS app we need to build a form that contain text input (sign up, contact detail, address detail). Sometimes the software keyboards will get in the way and cover part of the UI.

The simple solution is UITableView, UITableView will nicely handle this problem by reduce the table view size or more technical set the content inset to allocate space for keyboard. It also will scroll to the selected text field.

But at times we want to use a lot of custom layout which need to embed UIs in a scroll view or have a text view covers the entire screen.

Solution 1

Use notification center to capture keyboard show and hide event and allocate space accordingly. This is a solved problem, there are tons of solution in The gist of the solution look similar to this:

First Observe keyboard will show and hide notification, and don’t forget to remove notification in dealloc

for keyboardWillShow

The code will be similar for key board will hide method, simply set the insert to all zero

While we added a content inset we also added the same inset to scroll indicator inset or the scroll bar will end above the keyboard.

You can also animate layout constraints or frame change

Problem 2

What if the view is in a Popover or Form sheet?

Solution 2

It turned out that the solution is pretty simple. We need to figure out the view frame in respect to the app window and deduct the bottom space from the keyboard height.

This also works for the iPhone as well as the multi window mode in iPad, since the view frame and the application window frame will have the same maximum y value.