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.
compose().onKeyPress(
key: SwiftUI.KeyEquivalent,
options: {
action: SwiftUI.KeyPressResult;
}
)nonisolated func onKeyPress(
_ key: KeyEquivalent,
action: @escaping () -> KeyPress.Result
) -> some ViewParameters
The key to match against incoming hardware keyboard events.
options.action*SwiftUI.KeyPressResultThe action to perform. Return
.handledto consume the event and prevent further dispatch, or.ignoredto 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.
- onAppearAdds an action to perform before this view appears.
- onChangeAdds a modifier for this view that fires an action when a specific value changes.
- onContinueUserActivityRegisters a handler to invoke in response to a user activity that your app receives.
- onContinuousHoverAdds an action to perform when the pointer enters, moves within, and exits the view's bounds.
- onDisappearAdds an action to perform after this view disappears.
- onDragActivates this view as the source of a drag and drop operation.
- onDragSessionUpdatedSpecifies an action to perform on each update of an ongoing dragging operation activated by draggable(:) or anther drag modifiers.
- onDropDefines the destination of a drag and drop operation that handles the dropped content with a closure that you specify.
- onDropSessionUpdatedSpecifies an action to perform on each update of an ongoing drop operation activated by dropDestination(:) or other drop modifiers.
- onGeometryChangeAdds an action to be performed when a value, created from a geometry proxy, changes.
- onHingeChangeAdds an action to perform when the hinge context of the view hierarchy changes.
- onHoverAdds an action to perform when the user moves the pointer over or away from the view's frame.