Making UIScrollView Scrollable with keypad in iOS
byMaking UIScrollView Scrollable with Keyboard in iOS
One common challenge in iOS app development is handling user input when the on-screen keyboard is displayed.Register for Keyboard Notifications
Register for keyboard notifications in view controller. These notifications will inform us when the keyboard shows and hides.
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
Adjust Content Inset and Scroll View Content Offset
We will adjust the content inset and scroll view content offset when the keyboard shows and hides:
@objc func keyboardWillShow(_ notification: Notification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size {
let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
scrollView.contentInset = contentInsets
scrollView.scrollIndicatorInsets = contentInsets
}
}
@objc func keyboardWillHide(_ notification: Notification) {
scrollView.contentInset = UIEdgeInsets.zero
scrollView.scrollIndicatorInsets = UIEdgeInsets.zero
}
The UIScrollView allows to navigate through a larger content area by scrolling. When dealing with the on-screen keyboard, it becomes crucial to ensure a seamless user experience. One common challenge is adjusting the layout to accommodate the keyboard without obstructing the visibility of essential UI elements, such as text fields or text views.
The contentInset property of a UIScrollView plays a pivotal role in this adjustment. It represents the margins around the content of the scroll view, effectively expanding or shrinking the scrollable area. By dynamically modifying the contentInset based on the keyboard’s size and position, it allows to create a smooth and user-friendly interaction.
When the keyboard appears, setting a positive bottom inset in the contentInset allows the scroll view to expand its scrollable area, providing enough space for the keyboard without hiding any crucial content. This adjustment ensures that the user can still scroll through the entire content, even when the keyboard is active.
Conversely, when the keyboard disappears, resetting the contentInset to zero restores the scroll view to its original size, preventing any unintended content displacement.
You might also like: How to Detect Backspace Event in UITextfield and UITextview?