<!--
{
  "availability" : [
    "iOS: 17.0.0 -",
    "iPadOS: 17.0.0 -",
    "macCatalyst: 17.0.0 -",
    "macOS: 14.0.0 -",
    "tvOS: 17.0.0 -",
    "visionOS: 1.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "SwiftUI",
  "identifier" : "/documentation/SwiftUI/View/onKeyPress(phases:action:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "SwiftUI"
    ],
    "preciseIdentifier" : "s:7SwiftUI4ViewPAAE10onKeyPress6phases6actionQrAA0eF0V6PhasesV_AH6ResultOAHctF"
  },
  "title" : "onKeyPress(phases:action:)"
}
-->

# onKeyPress(phases:action:)

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

```
nonisolated func onKeyPress(phases: KeyPress.Phases = [.down, .repeat], action: @escaping (KeyPress) -> KeyPress.Result) -> some View
```

## Parameters

`phases`

The key-press phases to match (`.down`, `.repeat`, and
`.up`). The default value is `[.down, .repeat]`.

`action`

The action to perform. The action receives a value
describing the matched key event. 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

The following example shows a hint while someone holds the Option key,
and hides it again when they let go. It returns `.ignored` so that
other views still receive the event:

```
CanvasView()
    .focusable()
    .onKeyPress(phases: [.down, .up]) { keyPress in
        isShowingHint = keyPress.modifiers.contains(.option)
        return .ignored
    }
```

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)