---
title: "onKeyPress(_:action:)"
framework: swiftui
role: symbol
role_heading: Instance Method
path: "swiftui/view/onkeypress(_:action:)"
---

# onKeyPress(_:action:)

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

## Declaration

```swift
nonisolated func onKeyPress(_ key: KeyEquivalent, action: @escaping () -> KeyPress.Result) -> some View

```

## Parameters

- `key`: The key to match against incoming hardware keyboard events.
- `action`: The action to perform. Return .handled to consume the event and prevent further dispatch, or .ignored to allow dispatch to continue.

## Return Value

Return Value A modified view that binds hardware keyboard input when focused.

## Discussion

Discussion SwiftUI performs the action for key-down and key-repeat events.

## See Also

### Responding to keyboard input

- [onKeyPress(phases:action:)](swiftui/view/onkeypress(phases:action:).md)
- [onKeyPress(_:phases:action:)](swiftui/view/onkeypress(_:phases:action:).md)
- [onKeyPress(characters:phases:action:)](swiftui/view/onkeypress(characters:phases:action:).md)
- [onKeyPress(keys:phases:action:)](swiftui/view/onkeypress(keys:phases:action:).md)
- [KeyPress](swiftui/keypress.md)
