iOS development
keyboard management
user interface design
input field handling
mobile app development

Move a view up only when the keyboard covers an input field

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

The goal is not to move the whole screen every time the keyboard appears. The goal is to move content only when the active input field would actually be covered. The clean way to do that is to detect the keyboard frame, find the active field's position, calculate the overlap, and adjust only as much as necessary.

Prefer adjusting a constraint or scroll inset

On iOS, moving the root view frame directly is usually the least flexible option. A better pattern is to either:

  • adjust a bottom constraint
  • update a scroll view inset
  • scroll the active field into view

If your UI is form-like, a scroll view is often the easiest long-term answer. But if you already have a fixed layout and need a targeted upward shift, a bottom constraint works well.

Track the active input field

You need to know which text field or text view is being edited so you can measure whether that control is covered.

swift
1import UIKit
2
3final class FormViewController: UIViewController, UITextFieldDelegate {
4    @IBOutlet private weak var contentBottomConstraint: NSLayoutConstraint!
5    @IBOutlet private weak var emailField: UITextField!
6    @IBOutlet private weak var zipField: UITextField!
7
8    private weak var activeField: UIView?
9    private var originalBottomInset: CGFloat = 0
10
11    override func viewDidLoad() {
12        super.viewDidLoad()
13        originalBottomInset = contentBottomConstraint.constant
14
15        emailField.delegate = self
16        zipField.delegate = self
17
18        NotificationCenter.default.addObserver(
19            self,
20            selector: #selector(handleKeyboardWillChangeFrame(_:)),
21            name: UIResponder.keyboardWillChangeFrameNotification,
22            object: nil
23        )
24    }
25
26    func textFieldDidBeginEditing(_ textField: UITextField) {
27        activeField = textField
28    }
29
30    func textFieldDidEndEditing(_ textField: UITextField) {
31        if activeField === textField {
32            activeField = nil
33        }
34    }
35}

Without the active field reference, you cannot tell whether the keyboard is actually hiding the control the user is editing.

Calculate overlap instead of guessing

The right shift is based on geometry, not a hard-coded keyboard height. Convert both the keyboard frame and the active field frame into the view's coordinate system, then calculate the overlap.

swift
1@objc
2private func handleKeyboardWillChangeFrame(_ note: Notification) {
3    guard
4        let activeField,
5        let userInfo = note.userInfo,
6        let keyboardFrameValue = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue,
7        let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double,
8        let curveValue = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt
9    else {
10        return
11    }
12
13    let keyboardFrameInScreen = keyboardFrameValue.cgRectValue
14    let keyboardFrameInView = view.convert(keyboardFrameInScreen, from: nil)
15    let fieldFrameInView = activeField.convert(activeField.bounds, to: view)
16
17    let keyboardTop = keyboardFrameInView.minY
18    let fieldBottom = fieldFrameInView.maxY
19    let padding: CGFloat = 12
20    let overlap = max(0, fieldBottom + padding - keyboardTop)
21
22    contentBottomConstraint.constant = originalBottomInset + overlap
23
24    let options = UIView.AnimationOptions(rawValue: curveValue << 16)
25    UIView.animate(withDuration: duration, delay: 0, options: options) {
26        self.view.layoutIfNeeded()
27    }
28}

If overlap is zero, the field is already visible and the layout stays put. That is the key behavior the title is asking for.

Reset when the keyboard is gone

When editing finishes or the keyboard hides, restore the original layout instead of leaving the view shifted.

swift
1override func viewWillDisappear(_ animated: Bool) {
2    super.viewWillDisappear(animated)
3    NotificationCenter.default.removeObserver(self)
4}
5
6@objc
7private func resetLayoutForKeyboardHide() {
8    contentBottomConstraint.constant = originalBottomInset
9    view.layoutIfNeeded()
10}

In practice, many apps handle both show and hide from keyboardWillChangeFrameNotification, because the keyboard frame moves to the bottom of the screen when hiding. The important part is restoring the original constraint once there is no overlap.

Why this is better than moving the whole root view

Directly shifting view.frame.origin.y is tempting, but it tends to fight Auto Layout, safe areas, and nested containers. Constraint-based movement is easier to animate and easier to reason about when the screen rotates or the keyboard changes height.

That is also why scroll views remain the most robust option for larger forms. They solve the same visibility problem without pretending the whole screen must move as one block.

Common Pitfalls

The biggest mistake is moving the UI every time the keyboard appears, even when the active field is already visible. That creates distracting unnecessary motion.

Another issue is using a hard-coded keyboard height. Keyboard size changes with device, orientation, hardware keyboards, and input method.

Developers also forget coordinate conversion. Keyboard frames arrive in screen coordinates, while input fields are often measured in a local view hierarchy.

Finally, changing the root view frame directly often causes more layout problems than it solves in Auto Layout-driven screens.

Summary

  • Track the active input field so you know what needs to stay visible.
  • Compare the keyboard frame with the active field's frame and calculate the actual overlap.
  • Move the layout only by the amount needed, or not at all if there is no overlap.
  • Prefer bottom-constraint or scroll-view adjustments over moving the whole root view frame.
  • Reset the layout when the keyboard hides or the field is no longer active.

Related reading
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
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.