Fix: TextField Hidden Under Keyboard in SwiftUI

Fix: TextField Hidden Under Keyboard in SwiftUI

Written by

in

Quick answer: Wrap your form in a ScrollView and use .scrollDismissesKeyboard(.interactively) with a keyboard-aware bottom padding, or apply a ViewModifier that listens to UIResponder.keyboardWillShowNotification and adjusts content offset based on the keyboard frame minus safe area insets.

Why this happens

SwiftUI does not automatically scroll or resize views when the system keyboard appears. A VStack of TextField controls sits at fixed coordinates; when the keyboard slides up it simply covers the lower fields. The layout engine has no built-in knowledge of the keyboard frame, so developers must observe keyboard notifications and adjust padding or offset themselves.

The complication comes from safe-area insets (home indicator, tab bar, navigation bar) and the fact that keyboard height varies by device, orientation, and input mode (emoji, one-handed, hardware keyboard). A robust solution must subtract the bottom safe-area inset from the keyboard height and animate the change in sync with the system keyboard animation.

How to fix it

1. Modern iOS 17+ approach: ScrollView + scrollDismissesKeyboard

Starting with iOS 17, the simplest fix is to place the fields inside a ScrollView and enable the new dismiss behavior. The scroll view automatically keeps the focused field visible.

import SwiftUI

struct ContentView: View {
    @State private var fields = Array(repeating: "", count: 7)
    @FocusState private var focusedIndex: Int?

    var body: some View {
        ScrollView {
            VStack(spacing: 16) {
                ForEach(0..<fields.count, id: \.self) { i in
                    TextField("TextField \(i + 1)", text: $fields[i])
                        .textFieldStyle(.roundedBorder)
                        .focused($focusedIndex, equals: i)
                }
            }
            .padding()
        }
        .scrollDismissesKeyboard(.interactively)
    }
}

Requires iOS 17 / macOS 14. No manual notification handling needed.

2. ViewModifier using Combine (iOS 14–16 compatible)

For older deployments, observe keyboardWillShowNotification, keyboardWillChangeFrameNotification, and keyboardWillHideNotification. Use a GeometryReader to read the current view’s safe-area inset so the padding stops exactly above the home indicator or tab bar.

import SwiftUI
import Combine

private struct AdaptsToKeyboard: ViewModifier {
    @State private var currentHeight: CGFloat = 0

    func body(content: Content) -> some View {
        GeometryReader { proxy in
            content
                .padding(.bottom, currentHeight)
                .animation(.easeOut(duration: 0.16), value: currentHeight)
                .onAppear {
                    let show = NotificationCenter.default
                        .publisher(for: UIResponder.keyboardWillShowNotification)
                    let change = NotificationCenter.default
                        .publisher(for: UIResponder.keyboardWillChangeFrameNotification)
                    let hide = NotificationCenter.default
                        .publisher(for: UIResponder.keyboardWillHideNotification)

                    Publishers.Merge(show, change)
                        .compactMap { $0.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect }
                        .map { $0.height - proxy.safeAreaInsets.bottom }
                        .assign(to: &$currentHeight)

                    hide
                        .map { _ in CGFloat.zero }
                        .assign(to: &$currentHeight)
                }
        }
    }
}

extension View {
    func adaptsToKeyboard() -> some View {
        modifier(AdaptsToKeyboard())
    }
}

Usage:

struct MyForm: View {
    var body: some View {
        Form { /* your fields */ }
            .adaptsToKeyboard()
    }
}

Key points
– GeometryReader gives the view’s safe-area inset, not the window’s.
– Subtracting proxy.safeAreaInsets.bottom prevents double-padding when a tab bar or home indicator already reserves space.
– The animation(.easeOut(duration: 0.16)) matches the system keyboard curve.

3. Per-field precision with KeyboardGuardian (legacy but precise)

If you only want to shift enough to reveal the active field, track each field’s frame with a GeometryGetter preference key and compute the required offset in an ObservableObject.

import SwiftUI
import Combine

final class KeyboardGuardian: ObservableObject {
    @Published var rects: [CGRect] = []
    @Published var slide: CGFloat = 0
    private var cancellables = Set<AnyCancellable>()

    init(textFieldCount: Int) {
        rects = Array(repeating: .zero, count: textFieldCount)

        NotificationCenter.default
            .publisher(for: UIResponder.keyboardWillShowNotification)
            .merge(with: NotificationCenter.default.publisher(for: UIResponder.keyboardWillChangeFrameNotification))
            .compactMap { $0.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect }
            .sink { [weak self] kbFrame in
                guard let self = self else { return }
                let maxY = self.rects.map(\.maxY).max() ?? 0
                let overlap = maxY - (UIScreen.main.bounds.height - kbFrame.height)
                if overlap > 0 {
                    withAnimation(.easeOut(duration: 0.16)) { self.slide = -overlap }
                }
            }
            .store(in: &cancellables)

        NotificationCenter.default
            .publisher(for: UIResponder.keyboardWillHideNotification)
            .sink { [weak self] _ in
                withAnimation(.easeOut(duration: 0.16)) { self?.slide = 0 }
            }
            .store(in: &cancellables)
    }
}

struct GeometryGetter: View {
    @Binding var rect: CGRect
    var body: some View {
        GeometryReader { proxy in
            Color.clear
                .preference(key: RectPreferenceKey.self, value: proxy.frame(in: .global))
        }
        .onPreferenceChange(RectPreferenceKey.self) { rect = $0 }
    }
}

private struct RectPreferenceKey: PreferenceKey {
    static var defaultValue: CGRect = .zero
    static func reduce(value: inout CGRect, nextValue: () -> CGRect) { value = nextValue() }
}

Attach .background(GeometryGetter(rect: $guardian.rects[index])) to each TextField and apply .offset(y: guardian.slide) to the container.

How to prevent it

  • Always wrap long forms in a ScrollView (or List/Form) so content can scroll when space is limited.
  • Use @FocusState to programmatically dismiss the keyboard after submission instead of relying on the user to tap away.
  • Test with the Software Keyboard toggled off in the simulator (⌘⇧K) to verify hardware-keyboard layouts.
  • Run the Keyboard Layout Guide debug overlay (Xcode → Debug → View Debugging → Show Keyboard Layout Guide) to visualize safe-area conflicts.

FAQ

Does ScrollView alone solve the problem on iOS 16?

No. Prior to iOS 17 a plain ScrollView does not auto-scroll to the focused field. You still need a keyboard observer or a third-party library like KeyboardObserving.

Why subtract safeAreaInsets.bottom from the keyboard height?

The keyboard frame is reported in screen coordinates. The bottom safe-area inset (home indicator, tab bar) already pushes content up; adding the full keyboard height would double-count that space and leave a gap.

Can I use keyboardLayoutGuide instead of notifications?

UIKeyboardLayoutGuide exists in UIKit but has no direct SwiftUI equivalent as of iOS 17. The notification-based approach remains the standard cross-version solution.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.