UIScreen: keyboardchange event
The keyboardchange event fires when the keyboard's position or size is about to change.
Syntax
screen.addEventListener('keyboardchange', (event) => { })Event object
UIScreenKeyboardEvent. Besides type and target (this screen), it carries three read-only fields:
| Field | Type | Meaning |
|---|---|---|
frame | CGRect | Where the keyboard is when the animation ends, in screen coordinates, in pt. The keyboard's height is frame.height |
previousFrame | CGRect | Where the keyboard is when the animation starts |
duration | number | How long the keyboard animation lasts, in seconds |
Not cancelable. On iPhone the app fills the whole screen, so screen coordinates are the same as coordinates in the window.
When it fires
- Fires both when the keyboard appears and when it's dismissed, before
keyboardshowandkeyboardhiderespectively (tested). - Also fires when the keyboard's height changes while it's shown, for example when the user switches input methods or a suggestion bar appears. This case is not verified in the simulator.
- If all you care about is how much room the keyboard takes up right now, listening for this one event is enough.
Dispatched on the spot: listeners run inside the keyboard's animation. If a listener changes a view's frame, or changes constraints and then calls layoutIfNeeded(), those changes move along with the keyboard, with the same duration and timing curve, and you don't write an animation yourself (tested).
When JS dismisses the keyboard itself by calling endEditing(), the listeners have finished before endEditing() returns (tested).
Examples
const page = new UIViewController();
const bar = new UIView();
bar.frame = new CGRect(0, 800, 390, 56);
page.view.addSubview(bar);
const screen = /** @type {UIWindowScene} */ (application.scenes[0]).screen;
screen.addEventListener('keyboardchange', (e) => {
const event = /** @type {UIScreenKeyboardEvent} */ (e);
const top = Math.min(event.frame.y, screen.bounds.height);
bar.frame = new CGRect(0, top - 56, 390, 56);
});Effect: when the keyboard appears, is dismissed, or changes height, bar moves with it and stays on top of the keyboard; when the keyboard is dismissed it returns to the bottom of the screen.
Corresponding iOS API
UIKeyboardWillChangeFrameNotification.
See also
keyboardLayoutGuide: follow the keyboard with constraints instead of listening for eventsUIScreen