onKeyPress

Performs an action if the user presses a key on a hardware keyboard while the view has focus.

View ModifieriOS 17.0+macOS 14.0+tvOS 17.0+

Overloads

5 ways to call compose().onKeyPress(). Each is one SwiftUI overload, picked by the arguments you pass.

React
compose().onKeyPress(
  key: SwiftUI.KeyEquivalent,
  options: {
    action: SwiftUI.KeyPressResult;
  }
)
Swift
nonisolated func onKeyPress(
    _ key: KeyEquivalent,
    action: @escaping () -> KeyPress.Result
) -> some View

Parameters

  • The key to match against incoming hardware keyboard events.

  • options.action*SwiftUI.KeyPressResult

    The action to perform. Return .handled to consume the event and prevent further dispatch, or .ignored to allow dispatch to continue.

Return value

A modified view that binds hardware keyboard input when focused.

Discussion

SwiftUI performs the action for key-down and key-repeat events.

The following example plays or pauses a video when someone presses the space bar:

PlayerView(item: item)
    .focusable()
    .onKeyPress(.space) {
        player.togglePlayback()
        return .handled
    }

See also

More in Events and lifecycle.