skip to content

In UIKit, how does UIKeyboardLayoutGuide keep a promo-code text field above the keyboard, and what keyboard-notification code does it replace?

level: middleimportance: should knowfreq 55%

answer

  1. a guide that moves with the keyboard
  2. every view has one since iOS 15
  3. pin bottom to the guide's top
  4. off screen it meets the safe area
  5. undocked keyboards need an opt-in

basics

~20 s

Since iOS 15 every view has a keyboardLayoutGuide that tracks the docked keyboard; pinning the field's bottom to its topAnchor keeps it above the keyboard. It replaces observing keyboard frame notifications and adjusting a bottom constraint's constant by hand.

solid answer

~40 s

`UIView.keyboardLayoutGuide` (iOS 15) is a `UIKeyboardLayoutGuide`, a layout guide that represents the space the keyboard occupies. Constrain the promo-code field with `promoField.bottomAnchor.constraint(equalTo: view.keyboardLayoutGuide.topAnchor, constant: -12)` and the field follows the keyboard as it appears, hides or changes height. When the keyboard is off screen or undocked, the guide's top sits on the bottom of the safe area, so the same constraint keeps the field above the home indicator. Before iOS 15 you observed `UIResponder.keyboardWillChangeFrameNotification`, read `keyboardFrameEndUserInfoKey`, converted the frame into the view's coordinates and animated a bottom constraint's `constant` with the duration from the notification. For iPad's floating or split keyboard, set `followsUndockedKeyboard = true` and use the tracking guide's edge-based constraint sets.

code

swift · 22 lines
swift
import UIKit

final class PromoCodeViewController: UIViewController {
    private let promoField = UITextField()

    override func viewDidLoad() {
        super.viewDidLoad()
        promoField.borderStyle = .roundedRect
        promoField.placeholder = "Promo code"
        promoField.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(promoField)

        let margins = view.layoutMarginsGuide
        NSLayoutConstraint.activate([
            promoField.leadingAnchor.constraint(equalTo: margins.leadingAnchor),
            promoField.trailingAnchor.constraint(equalTo: margins.trailingAnchor),
            // Sits 12 pt above the keyboard, or above the safe area when it is hidden.
            promoField.bottomAnchor.constraint(
                equalTo: view.keyboardLayoutGuide.topAnchor, constant: -12)
        ])
    }
}

go deeper

for a junior

Recall the one constraint: the field's bottom anchor to view.keyboardLayoutGuide.topAnchor with a small negative constant, available since iOS 15.

for a middle

Explain where the guide sits when the keyboard is hidden or undocked, and what the notification code it replaces had to do.

for a senior

Cover iPad cases with followsUndockedKeyboard and edge-based constraint sets, and retire per-screen keyboard observers in a migration.

for a principal

Decide whether the deployment target allows deleting every keyboard observer and making the guide the team's only pattern for keyboard avoidance.

## The problem the guide solves When a text field becomes first responder, the software keyboard slides up over the bottom of the screen. A promo-code field pinned to the bottom of the safe area ends up hidden behind it. The app has to move the field, keep moving it as the keyboard changes height (a different keyboard, the predictive bar, a hardware keyboard attached) and put it back when the keyboard hides. ## The old way: keyboard notifications Before iOS 15 this was manual work with notifications posted through `NotificationCenter`: 1. Observe `UIResponder.keyboardWillChangeFrameNotification` (or the will-show and will-hide pair). 2. Read the final keyboard frame from `UIResponder.keyboardFrameEndUserInfoKey` in the notification's `userInfo`. 3. Convert that frame, which the header says is in screen coordinates, into the view's coordinate space and work out the overlap. 4. Set the `constant` of the field's bottom constraint and call `layoutIfNeeded()` inside an animation using `keyboardAnimationDurationUserInfoKey`. Each screen repeated this code, and each copy could get split view, rotation or an undocked keyboard wrong in its own way. ## The keyboard layout guide iOS 15 added `keyboardLayoutGuide` to every `UIView`. It returns a `UIKeyboardLayoutGuide`, a subclass of `UITrackingLayoutGuide`, which is itself a `UILayoutGuide`. Like the safe area guide, it is a rectangle you constrain against, but UIKit moves it to match the keyboard. Its documented behaviour: - While the keyboard is **on screen and docked**, the guide follows it, so its `topAnchor` is the keyboard's top edge. - When the keyboard is **off screen** or **undocked**, the guide's `topAnchor` is tied to the bottom of the view's `safeAreaLayoutGuide`. - With `usesBottomSafeArea` (iOS 17, default `true`) set to `false`, the off-screen guide uses the view's own bottom edge instead of the safe area. That second rule is why one constraint is enough: `field.bottom = keyboardLayoutGuide.top - 12` puts the field 12 points above the keyboard while it is up, and 12 points above the home indicator when it is down. No notification observer, no frame conversion, no constant to update. ## Floating and split keyboards On iPad the keyboard can float or split. By default the guide ignores an undocked keyboard and stays on the safe area. Set `followsUndockedKeyboard` to `true` and it tracks the keyboard wherever it is. Because a floating keyboard can sit anywhere, `UITrackingLayoutGuide` lets you register constraints that switch themselves on and off by edge: - `setConstraints(_:activeWhenNearEdge:)`: active when the keyboard is close to that edge. - `setConstraints(_:activeWhenAwayFrom:)`: active when it moves away. The header describes the states: docked or off screen counts as near only the bottom edge; full-width but undocked, or split, is away from the side edges and can be near the top or the bottom; floating can be near one or two adjacent edges. | Property | Default | Since | Effect | |---|---|---|---| | `followsUndockedKeyboard` | `false` | iOS 15 | track floating and split keyboards too | | `usesBottomSafeArea` | `true` | iOS 17 | off-screen guide sits on the safe area rather than the view's bottom | | `keyboardDismissPadding` | `0` | iOS 17 | extra height above the keyboard where a scroll-to-dismiss gesture starts | ## Working with scroll views For a long form, the field usually lives in a scroll view. Pin the scroll view's bottom to `keyboardLayoutGuide.topAnchor` and its visible area shrinks to the space above the keyboard. When the scroll view's `keyboardDismissMode` lets the user drag the keyboard away, `keyboardDismissPadding` starts that dismissal a little above the keyboard's edge. Making the field first responder, and resigning it, is responder-chain territory rather than layout. ## Deploying back to iOS 17 An app that deploys to iOS 17 has all three properties, so it can use the guide everywhere and delete its keyboard observers. Code that still supports a release older than iOS 15 needs the guide behind an availability check, with the notification approach as the fallback. A migration of an existing screen usually takes four steps: 1. Delete the keyboard notification observers and the code that converted frames. 2. Re-point the bottom constraint from the safe area guide to `view.keyboardLayoutGuide.topAnchor`, keeping its spacing as the constant. 3. Remove the stored reference that existed only so the observer could change the constant. 4. Check the screen with the software keyboard, a hardware keyboard and, on iPad, a floating keyboard.

  • Why does the promo-code field not drop behind the home indicator when the keyboard hides?
    When the keyboard is off screen, `UIKeyboardLayoutGuide` ties its top anchor to the bottom of the view's `safeAreaLayoutGuide`; that is the `usesBottomSafeArea` default, a property added in iOS 17. The same constraint therefore keeps the field above the safe area with no extra code. Setting the property to `false` would let the field sit on the view's bottom edge instead.
  • What changes on iPad when the user floats the keyboard?
    By default nothing: the guide follows only a docked keyboard and otherwise stays on the safe area. Setting `followsUndockedKeyboard = true` makes it track the floating keyboard, and `setConstraints(_:activeWhenNearEdge:)` and `setConstraints(_:activeWhenAwayFrom:)` let you swap layouts by which edge the keyboard is near.

  • UIKeyboardLayoutGuide needs keyboard notifications to update its position.
  • When the keyboard hides, the guide collapses to the very top of the view.
  • The guide follows a floating iPad keyboard with its default settings.
  • keyboardLayoutGuide needs iOS 17, so most apps cannot use it yet.
  • Keyboard notification frames are already in the view's own coordinates.

Assumes iOS 15 or later for keyboardLayoutGuide, and iOS 17 for usesBottomSafeArea and keyboardDismissPadding; checked against the iOS 27.1 SDK.