How to listen for key presses in a MacOS SwiftUI app

Add the "focusable()" modifier to a view, followed by any relevant "onKeyPress" modifiers.

Oscar de la Hera Gomez
Written by Oscar de la Hera Gomez
First published on 10/20/2024 at 10:15
Last Updated on 10/20/2024 at 11:28
<p>Two flowers that represent SwiftUI and XCode. Beneath them sits the text "MacOS Key Pressed."</p>

Add the "focusable()" modifier to a view, followed by any relevant "onKeyPress" modifiers.

SubscribeDownload Open Source Project
<p>An image of the sample code found below.</p>

The example below demonstrates how to listen for key presses.

It is fundamental that you apply the "focusable()" modifier to the view before the key press modifier, as if you don't you may not be able to listen for events.

To learn more about the focusable modifier and onKeyPress modifier, consult the links below.

Apple Developer: onKeyPress(_: action:)Apple Developer: focusable(_:)

Additionally, if key presses are not always registering, you may need to use an @FocusState property wrapper to guarantee that the key press is registered.

To learn more consult the tutorial below.

How to place focus on a view in SwiftUI

Looking to learn more about things you can do with Swift, SwiftUI or XCode?

Search our blog to find educational content on learning how to use Swift, SwiftUI or XCode.

Search our Blog

Any Questions?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.
SubscribeContact UsVisit our BlogView our ServicesView our Work

Partner with us

We would love to get to know you and see how we can help your organization with its goals and needs.
Let's Talk

Stay Informed

Get occasional updates about our company, research, and product launches.
Subscribe