Scrolling an iOS Text View When the Keyboard Appears
A common issue iOS developers run into is dealing with the onscreen keyboard. The keyboard appears and blocks what you’re typing.
The fix is to scroll the text view when the keyboard appears. The code to do this is not too hard. iOS posts a notification when the keyboard appears and when the keyboard disappears. Write a function to handle each notification. Scroll the text view when the keyboard appears and return it to its original position when the keyboard disappears.
Handling the Keyboard Appearing Notification
You must write the function keyboardWasShown
. This function gets called when the keyboard appears.
There are two things to do in keyboardWasShown
to scroll the text view. First, set the text view’s content inset so the bottom edge is the keyboard’s height. Second, set the scroll indicator insets to the text view’s content inset.
@objc func keyboardWasShown(notification: NSNotification) {
let info = notification.userInfo
if let keyboardRect = info?[UIResponder.
keyboardFrameBeginUserInfoKey] as? CGRect {
let keyboardSize = keyboardRect.size
textView.contentInset = UIEdgeInsets(top: 0, left: 0,
bottom: keyboardSize.height, right: 0)
textView.scrollIndicatorInsets = textView.contentInset
}
}
Swift functions that work with notifications require the @objc
keyword at the start of the function declaration. The userInfo
property of the notification contains the rectangle where the keyboard appears on the screen.
Use the keyboard rectangle to get the keyboard’s height. Set the text view’s bottom edge inset to the keyboard’s height. The text view will scroll when the text insertion point gets near the top of the keyboard.
Handling the Keyboard Hiding Notification
You must write the function keyboardWillBeHidden
. This function gets called when the person entering text hides the keyboard.
When the keyboard disappears, set the text view’s content inset back to all zeroes. Set the text view’s scroll indicator insets to the text view’s content inset.
@objc func keyboardWillBeHidden(notification: NSNotification) {
textView.contentInset = UIEdgeInsets(top: 0, left: 0,
bottom: 0, right: 0)
textView.scrollIndicatorInsets = textView.contentInset
}
Example Project
I have a text editor project on GitHub to see the keyboard handling code in practice.