I am trying to create an application for OS X using Swift and Cocoa. I want the application to respond to key events without the focus being on/in a text field. I created a new Cocoa project with storyboards in Xcode, and have modified the ViewController.swift class to the following:
import Cocoa
class ViewController: NSViewController {
override func mouseDown(theEvent: NSEvent) {
println( "Mouse Clicked" )
}
override func keyDown(theEvent: NSEvent) {
println( "Key Pressed" )
}
override func viewDidLoad() {
super.viewDidLoad()
}
override var representedObject: AnyObject? {
didSet {
}
}
}
When I run the program, I get console output when I click on the window, but I don't get any console output when I press any keys.
So my questions are: Why does my program respond to mouse events but not key events? What extra steps do I need to do for key events to work as the mouse events do?
It appears that my view controller is in the responder chain since it intercepts the mouse events, so that doesn't seem to be the problem. I have found other answers on here on SE saying I need to subclass the NSView or NSWindow class. Is it possible to get key events without doing that?
Thanks in advance.
EDIT: In addition to the accepted answer, Swift - Capture keydown from NSViewController is a great, clear solution.