KeyPress
A hardware keyboard event that a focused view receives.
Declaration
struct KeyPressOverview
The onKeyPress(phases:action:) family of modifiers passes a value of this type to your action. Read key and modifiers to decide what to do, then return KeyPress.Result.handled to consume the event or KeyPress.Result.ignored to let other views receive it.
The following example removes the selected item when someone presses Delete, clears the selection on Escape, and leaves every other key to the rest of the app:
LibraryView(selection: $selection)
.focusable()
.onKeyPress(phases: .down) { keyPress in
switch keyPress.key {
case .delete:
library.remove(selection)
return .handled
case .escape:
selection = nil
return .handled
default:
return .ignored
}
}A view only receives key presses while it has focus, so pair these modifiers with focusable(_:) or another source of focus.
To respond to the arrow keys, use onMoveCommand(perform:) instead. That modifier also responds to the Siri Remote on tvOS.