Swift
Keyboard Management
TextField
iOS Development
User Interface

Move textfield when keyboard appears swift

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

On iOS, keyboards can cover text fields near the bottom of the screen. A robust fix is adjusting scroll insets or constraints when keyboard frame changes, not manually shifting the entire root view by fixed values. Modern implementations should also handle safe areas and hardware keyboard scenarios.

Core Sections

Preferred Approach with UIScrollView

If your form is inside a scroll view, update content insets when keyboard appears.

swift
1import UIKit
2
3class FormViewController: UIViewController {
4    @IBOutlet weak var scrollView: UIScrollView!
5
6    override func viewDidLoad() {
7        super.viewDidLoad()
8        NotificationCenter.default.addObserver(
9            self,
10            selector: #selector(handleKeyboard),
11            name: UIResponder.keyboardWillChangeFrameNotification,
12            object: nil
13        )
14    }
15
16    @objc private func handleKeyboard(_ note: Notification) {
17        guard let info = note.userInfo,
18              let frame = info[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }
19
20        let keyboardInView = view.convert(frame, from: nil)
21        let overlap = max(0, view.bounds.maxY - keyboardInView.minY)
22
23        scrollView.contentInset.bottom = overlap
24        scrollView.verticalScrollIndicatorInsets.bottom = overlap
25    }
26
27    deinit {
28        NotificationCenter.default.removeObserver(self)
29    }
30}

This preserves layout while keeping focused fields accessible.

Scroll Active Field into View

When editing begins, scroll so the current field is visible above keyboard.

swift
1extension FormViewController: UITextFieldDelegate {
2    func textFieldDidBeginEditing(_ textField: UITextField) {
3        let rect = textField.convert(textField.bounds, to: scrollView)
4        scrollView.scrollRectToVisible(rect.insetBy(dx: 0, dy: -20), animated: true)
5    }
6}

This avoids users manually dismissing keyboard to continue input.

Constraint-based Layout Alternative

If you are not using scroll views, adjust a bottom constraint tied to content container.

swift
1@IBOutlet weak var bottomConstraint: NSLayoutConstraint!
2
3@objc private func handleKeyboard(_ note: Notification) {
4    guard let frame = note.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }
5    let keyboardInView = view.convert(frame, from: nil)
6    bottomConstraint.constant = max(0, view.bounds.maxY - keyboardInView.minY)
7    view.layoutIfNeeded()
8}

Use animation duration and curve from keyboard notifications for smooth transitions.

Handle Edge Cases

Support external keyboards and split keyboards where overlap may be zero or irregular. Also consider orientation changes and dynamic type causing field positions to move.

Testing should include small screens and long forms. Keyboard overlap bugs often appear only in specific device sizes.

Clean Notification Lifecycle

Register observers in viewWillAppear and remove in viewWillDisappear for reusable controllers. This avoids duplicate callbacks and memory issues.

swift
1override func viewWillAppear(_ animated: Bool) {
2    super.viewWillAppear(animated)
3    // add observer
4}
5
6override func viewWillDisappear(_ animated: Bool) {
7    super.viewWillDisappear(animated)
8    // remove observer
9}

Modern API Option with Keyboard Layout Guide

On newer iOS versions, keyboardLayoutGuide can simplify keyboard-aware constraints. This reduces notification-heavy code for certain layouts.

swift
1if #available(iOS 15.0, *) {
2    view.keyboardLayoutGuide.followsUndockedKeyboard = true
3    bottomConstraint.isActive = false
4    textField.bottomAnchor.constraint(
5        lessThanOrEqualTo: view.keyboardLayoutGuide.topAnchor,
6        constant: -12
7    ).isActive = true
8}

This is cleaner for simple forms and automatically tracks keyboard position changes.

Animation Synchronization

When using notification-driven updates, animate constraint changes with keyboard timing values from notification payload.

swift
1if let duration = note.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double,
2   let curve = note.userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt {
3    UIView.animate(withDuration: duration,
4                   delay: 0,
5                   options: UIView.AnimationOptions(rawValue: curve << 16),
6                   animations: {
7        self.view.layoutIfNeeded()
8    })
9}

Matching keyboard animation makes UI transitions feel native and prevents jumpy movement.

Accessibility testing should include VoiceOver focus movement while keyboard is visible. Focus behavior can break even when layout visually looks correct, especially in long forms with dynamic cells.

Automated UI tests that type into bottom fields provide durable protection against keyboard-overlap regressions after layout refactors.

Robust keyboard handling significantly improves form completion rates in mobile apps.

Centralized keyboard utilities help teams enforce consistent behavior across many form screens.

Reliable behavior here directly improves user trust.

Common Pitfalls

  • Moving the root view frame by hardcoded pixels.
  • Ignoring safe-area insets and keyboard frame conversion.
  • Forgetting to remove observers and receiving duplicate callbacks.
  • Handling only keyboard show and not frame-change notifications.
  • Skipping tests on small-screen devices where overlap is most visible.

Summary

  • Prefer scroll inset or constraint adjustments over manual root-view shifts.
  • Listen to keyboard frame change notifications for reliable behavior.
  • Keep active input visible with targeted scrolling.
  • Account for safe area, orientation, and external keyboard cases.
  • Manage observer lifecycle to avoid callback duplication.

Course illustration
Course illustration

All Rights Reserved.