KeyPress
A hardware keyboard event that a focused view receives.
Declaration
type KeyPress = { readonly characters: string; readonly debugDescription: string; readonly key: KeyEquivalent; readonly modifiers: EventModifiers; readonly phase: KeyPressPhases; };struct KeyPressProperties
characters*stringThe characters generated by the pressed key as if no modifier key applies.
debugDescription*stringA textual representation of this instance, suitable for debugging.
key*KeyEquivalentThe key equivalent value for the pressed key.
modifiers*EventModifiersThe set of modifier keys the user held in addition to the pressed key.
phase*KeyPressPhasesThe phase of the key-press event (
.down,.repeat, or.up).
Overview
The View.onKeyPress(phases:action:) family of modifiers passes a value
of this type to your action. Read KeyPress.key and
KeyPress.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 View.focusable(_:) or another source of focus.
To respond to the arrow keys, use View.onMoveCommand(perform:) instead.
That modifier also responds to the Siri Remote on tvOS.
From Apple’s SwiftUI documentation. Code samples there are Swift.
Used by
See also
More in Other values.
- AxisThe horizontal or vertical dimension in a 2D coordinate system.
- AxisSetAn efficient set of axes.
- ButtonRoleA value that describes the purpose of a button.
- CapsuleA capsule shape aligned inside the frame of the view containing it.
- CircleA circle centered on the frame of the view containing it.
- ConcentricRectangleA shape whose corners you configure, individually or uniformly, to be squared, rounded, or concentric relative to a container shape's corners.
- ContentMarginGuideA guide for resolving the content margins for a view.
- ContentMarginPlacementThe placement of margins.
- ContentModeConstants that define how a view's content fills the available space.
- DatePickerComponents
- DatePickerComponents2The date and time components that a date picker shows.
- DeviceHingeA type encapsulating the state of a single hinge.