1

I am trying to write a simple program in Swift 3 where I need to perform an action every time the user presses an arrow key. After a bit of research, I found that the method I needed to use was keyDown(with event: NSEvent) ; the problem is that it simply doesn't get called whenever I press any key.

Here's my code

import Cocoa let LEFT: UInt16 = 123 let RIGHT: UInt16 = 124 let DOWN: UInt16 = 125 let UP: UInt16 = 126 class GameViewController: NSViewController { ... override func keyDown(with event: NSEvent) { print("abc") switch event.keyCode { case LEFT: print("left") break case RIGHT: print("right") break case DOWN: print("down") break case UP: print("up") break default: print("other") super.keyDown(with: event) break } print("Key with number: \(event.keyCode) was pressed") } } 

I tried pressing all the arrow keys, and other key to test if my arrow keys had a problem, but nothing happened - except me getting the error sound from macOS.

I don't know where the problem could be from - I'm rather new to Swift, so it may be something quite obvious that I am not seeing. Do you guys have any idea of what I am doing wrong ?

Many thanks in advance

1
  • Your class must be part of the responder chain. You will probably find what you need in Cocoa Event Handling Guide. Commented Dec 25, 2016 at 12:45

1 Answer 1

2

I notice that you've implemented the keyDown method in the code of your view controller. That's actually the incorrect place—that method should go inside the code of the view, not the view controller. If you aren't currently using a custom view (with code you can modify), then you should create a new subclass.

Sign up to request clarification or add additional context in comments.

1 Comment

@Luigi Do you need any help setting this up?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.