How to listen for key presses in a MacOS SwiftUI app

Oscar de la Hera Gomez
Two flowers that represent SwiftUI and XCode. Beneath them sits the text "MacOS Key Pressed."

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

An image of the sample code found below.

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.

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.

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.

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.
delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details