KeyPress

A hardware keyboard event that a focused view receives.

StructureiOS 17.0+macOS 14.0+tvOS 17.0+KeyPress in SwiftUI

Declaration

React
type KeyPress = { readonly characters: string; readonly debugDescription: string; readonly key: KeyEquivalent; readonly modifiers: EventModifiers; readonly phase: KeyPressPhases; };
Swift
struct KeyPress

Properties

  • characters*string

    The characters generated by the pressed key as if no modifier key applies.

  • debugDescription*string

    A textual representation of this instance, suitable for debugging.

  • The key equivalent value for the pressed key.

  • modifiers*EventModifiers

    The set of modifier keys the user held in addition to the pressed key.

  • The 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.