PROGRAMMING
iOS Tricks: Automatic Keyboard Handling
How to manage the keyboard automatically and forget about it.
Every time we write an iOS app there is at least one screen where the user has to input something: their username and password to log in, their name in a game, a note, …
The keyboard handling is a basic use case but Apple forces us to manage it manually. This somehow annoys me so let’s see how we can automate this, once and for all.
How Does It Work?
The first step in solving a problem is to understand how the process is working at the moment.
When we add a control on the screen — such as a UITextField
— , we launch the app and we tap on the control, the keyboard appears and we are able to input some text.
What has happened is that the system reacted to our touch and set the UITextField
as the firstResponder
for the app. It is the first component that is queried to respond to user input. Here how it looks like in a small video.
As you may see from the video, a couple of questions naturally arise:
- The keyboard has appeared, but why are the components hidden behind it?
- How can we dismiss the keyboard once the user…