iOS to macOS: Reading keyboard input

October 10, 2016

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

Swift

1

2

3

overridevaracceptsFirstResponder: Bool{returntrue}

overridefuncbecomeFirstResponder()->Bool{returntrue}

overridefuncresignFirstResponder()->Bool{returntrue}

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

override func keyDown(with event:NSEvent){

ifkeyIsDown==true{

return

}

keyIsDown=true

ifevent.keyCode==1{

print("s key pressed")

}elseifevent.keyCode==49{

print("spacebar pressed")

}

}

override func keyUp(with event:NSEvent){

keyIsDown=false

ifevent.keyCode==1{

print("s key released")

}elseifevent.keyCode==49{

print("spacebar released")

}

}

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”

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!