Updated about 22 hours ago | GitHub
On this page

Registering for Keyboard Events

Basic Use Case

Keyboard GIF | 250

Often, you will have to rearrange views when the keyboard is shown or hidden to ensure that the appropriate views and controls are visible while the user is typing. To achieve this, we will register for the keyboard events which are fired when the keyboard is shown or hidden.

The system posts these events as notifications through NotificationCenter, which broadcasts them to registered observers. This mechanism is commonly used for system events like keyboard, device rotation, and coming back from or going into standby. For example, when coming back from standby, it’s common to refresh the network data of the view controller.

Step 1: Register for the keyboard events

Within the viewDidLoad method, register the view controller as an observer of the keyboard-will-show and keyboard-will-hide notifications. Each registration names a method on the view controller that runs when that notification fires.

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)

Then add the two handler methods to the view controller. #selector can only refer to methods that are available to the Objective-C runtime, so mark each handler with @objc.

@objc func keyboardWillShow(_ notification: Notification) {
    // Any code you put in here will be called when the keyboard is about to display
}

@objc func keyboardWillHide(_ notification: Notification) {
    // Any code you put in here will be called when the keyboard is about to hide
}

Because the observer is the view controller itself rather than a closure, there is no escaping closure capturing self. Apps that target iOS 9 or later don’t need to unregister observers added this way. The system cleans them up automatically. (If you use the closure-based addObserver(forName:object:queue:using:) instead, you must keep the returned observer object and remove it yourself. If self stores that observer object, capture self weakly inside the closure to avoid a retain cycle.)

Step 2: Add the Views You Want to Move When the Keyboard Appears.

In this use case, we want to move several views the same offset amount when the keyboard is shown. To avoid having to animate each view individually, we can contain all the views inside another view.

Step 3: Create Outlets For the Views You Want to Offset.

  • Create an outlet for the fieldSuperview. Drag from fieldSuperview in the Document Outline to your ViewController swift file.
    Create outlet for fieldSuperview

Step 4: Define Variables

Near the top of the ViewController, where you create outlets, define variables for the initial y position of the text field and the offset amount.

var initialY: CGFloat!
var offset: CGFloat!

Define Variables

Step 5: Assign Values to Variables

Within the viewDidLoad() method, give your offset variable a value. This is the amount that your view will be offset when the keyboard is shown. Remember, going “up” on the screen is decreasing the Y value amount.

offset = -50

Next, record the initial y position of the fieldSuperview. Wait until the view has been laid out to do this: in viewDidLoad(), views still have the default size they were loaded with, which can differ from their final on-screen layout. Override viewDidLayoutSubviews() and record the position the first time it runs, so later layout passes don’t overwrite it.

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    if initialY == nil {
        initialY = fieldSuperview.frame.origin.y
    }
}

The GIF below shows an earlier version of this step that recorded initialY in viewDidLoad().

Give Variables Values

Step 6: Offset the views When Keyboard is Shown.

keyboardWillShow demo|150

Inside the keyboardWillShow(_:) method from Step 1, offset the y position of the fieldSuperview using your offset value.

fieldSuperview.frame.origin.y = initialY + offset

NOTE: Setting the frame directly works when fieldSuperview isn’t positioned with Auto Layout constraints. If it is, the next layout pass moves it back, because by default layoutSubviews() sets each subview’s frame to the rectangle the Auto Layout engine calculates. On iOS 15 and later, you can instead constrain your views to the view’s keyboardLayoutGuide, which tracks the keyboard’s position, and Auto Layout moves them as the keyboard appears and disappears. See Apple’s Adjusting your layout with keyboard layout guide for examples.

NOTE: In this example, we are offsetting our views by an arbitrary amount. Sometimes you will want to offset your views based on the actual dimensions of the keyboard. In that case, you can get the frame of the keyboard, (a CGRect), like this…

let frame = (notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
    // do stuff based on the keyboard frame

Note: If the onscreen keyboard doesn’t appear when you click in the text field, the simulator is probably treating your Mac’s keyboard as a connected hardware keyboard. While a device is in hardware-keyboard mode, the software keyboard doesn’t appear when you select a text field. To bring it back:

  • Xcode 27 and later: Running your app on a simulator opens it in Device Hub. Choose the Toggle Software Keyboard menu item, or turn off the Simulate Hardware Keyboard menu item. Xcode 27.2 also adds a Hardware Keyboard Simulation option to Device Hub’s app settings.
  • Xcode 26 and earlier: In the Simulator app, choose I/O > Keyboard > Toggle Software Keyboard, or press cmd + k.

Step 7: Move View Back When Keyboard is Hidden

Now we will simply move the UITextField back to its original y position when the keyboard is hidden. Do this inside the keyboardWillHide(_:) method from Step 1.

fieldSuperview.frame.origin.y = initialY

Step 8: Hide the Keyboard When Tapping Outside the TextField

kb hide show gif|150

If you run the simulator now, you notice that when you click on the text field it will animate up as it should, but when you click away you cannot hide the keyboard. So we need to have the keyboard hide event triggered. A common way to do this is to tap away from the text field to trigger a keyboard hide.

  • Drag and drop a UITapGesture recognizer from the Object Library to the background view.
  • Ctrl+click and drag from the Tap Gesture Recognizer to the View Controller shown in the assistant editor. We will select the Action option and name the handler didTap.
  • Within the didTap method we simply have the line…
view.endEditing(true)

This dismisses the keyboard, which posts UIResponder.keyboardWillHideNotification and calls the keyboardWillHide(_:) method from Step 1.

Add tap to hide keyboard gif