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.

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.