The Battle Between TextFields and the Keyboard
When not using a UITableViewController you may have noticed an issue where your text field, if located lower on the screen gets hidden when the keyboard appears on screen.
Thankfully, there is a quick fix for this when used in conjunction with a scroll view. If you haven’t quite mastered scroll views yet, check out my article on how to add a scroll view.
In this example, I will start out with a View Controller with a scroll view, a label and 3 text fields.
First, you will need to add two observers, one to listen for when the keyboard will show and another for when the keyboard will hide.
This code will listen for the notifications and execute the keyboardWillShowOrHide function when the notification is posted.
The notification for when the keyboard will show will also include the keyboard size which will be used in the function to adjust the content view so that the text field will be displayed above the keyboard.
The notification for when the keyboard will hide will reverse the adjustment of the content view.
So to recap, when the text field is tapped, a notification is sent and the observer will call the function that will scroll the view up so the text field moves above the keyboard.
* The +15 in the code below is just to give it a little padding above the keyboard.
For good measure, I also added an unregisterFromAllNotifications function to remove the Observer when the view will disappear.
Now that we have the functions in place it’s time to get down to business. First up you will need to add an IBOutlet for the scrollView and connect it in your View Controller.
Next, call the registerForKeyboardNotifications function in viewDidLoad.
* We will get to the hideKeyboardTappedAround function call later. That’s a little added bonus!
Then, call the unregisterFromAllNotifications function for when the viewWillDisappear. That’s it for making your text field move above the keyboard!
There’s a little saying, what goes up must come down, and so it is with the keyboard. To make the keyboard go away, add the two functions below and when you click anywhere outside of the textfield or keyboard, the keyboard will be dismissed. The battle has been won!
If you are looking for more bells and whistles, check out IQKeyboardManager.