UIScrollView
keyboard handling
iOS development
scroll view adjustment
Swift programming

How do I scroll the UIScrollView when the keyboard appears?

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

When developing iOS applications, you'll often encounter views with text fields or text views, especially forms, where users are required to input data. A common problem arises when the on-screen keyboard appears; it can obscure the text fields, leading to a poor user experience. To mitigate this, you might want to move or scroll the content of a `UIScrollView` (or its subclass such as `UITableView` or `UICollectionView`) so that the active text field is still visible. Let's delve into the approach and steps necessary to achieve this.

Key Concepts

  1. Keyboard Notification: Listen for keyboard appearance and disappearance notifications.
  2. Adjust Content Insets: Increase `UIScrollView`'s content inset to accommodate the keyboard.
  3. Scrolling to Visibility: Adjust the scroll position so the active field becomes visible.

Implementing Keyboard-aware UIScrollView

To handle the keyboard events, you'll typically use notifications. Here's a step-by-step guide.

1. Observe Keyboard Notifications

First, register the view controller (or any appropriate object) to observe keyboard notifications. This is usually done in the `viewWillAppear` method:

  • Autolayout Constraints: Make sure that constraints do not create conflicts when adjusting the scroll view's insets.
  • Landscape Mode: Consider testing and adjusting for landscape mode as the keyboard occupies more space horizontally.
  • Custom Keyboard Frames: Custom keyboards might have different heights. Always rely on the `keyboardFrameEndUserInfoKey` for accurate dimensions.
  • Dynamic Changes: Handle dynamic keyboard dismissals, such as when hardware keyboards are connected.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms