Member-only story
Detecting Key Presses in macOS Apps using SwiftUI
Explanation and Code Examples
Detecting keystrokes/presses in macOS apps can be quite a pain, as the code isn’t all that straightforward. As of the time of writing, even ChatGPT doesn’t know how to tackle this.
In this article, I’d like to show you how it’s done, providing plenty of examples to make integrating it into your apps easier.
(My latest book “macOS App Development: The SwiftUI Way” is now available. Grab your copy today!)
Keyboard Mapping
First of all, copy the following CGKeyCode
extension to your macOS app project. It enhances the capabilities of the CGKeyCode
enumeration by providing methods to check for key presses.
Detect the Key Press
Next, you’ll need to accurately detect the keypress based on the mapping provided above.
Below an event listener on the keyDown
is created.
NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in
if Int(event.keyCode) == CGKeyCode.kVK_Space {
self.message = “You’ve hit the Space key”
}
return event
}