iOS to macOS: Reading keyboard input

iOS to macOS: Reading keyboard input

Coming from iOS go macOS, I wanted to read keyboard input in my macOS application. Not from a textfield but rather from the window itself. I thought this would be an easy task. After some trial and error, Googling, and then some StackOverflow fishing, I managed to get this to work. It wasn’t exactly straightforward for me to get but now that I did, I’d like to share the code that makes it work.

In my ViewController.swift file, I set up a few delegate callbacks

In my viewDidLoad, I added event monitoring (which eluded me for some time).

I then added keyUp and keyDown functions for the NSViewController itself.

I have a class variable (keyIsDown) which prevents keyboard repeats to flood the methods. Set that to false at the start.

This works a treat – and I didn’t have to subclass NSView, do anything in AppDelegate, etc. It’s clean, legible, and it does exactly what you’d expect it to do. This is for a single windowed application.

2 Replies to “iOS to macOS: Reading keyboard input”

  1. Sir, you are a god. I’ve been trying to get keystroke events working for days. Apple docs and StackOverflow are usually out of date, incomplete, or outright wrong, and trial and error coding is impossible when the storyboard and the viewController seem to be completely disconnected from each other. Thank you. Live long and prosper!

  2. This worked for me, except I had to add a condition to return nil as the event in case I handled it in my callbacks. Otherwise would get the macOS default “key not recognized” bell sound.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.