andertonslase andertonslase - 4 months ago 51
Swift Question

Detecting key press event in Swift

I'm trying to find a way to detect if a key (on a keyboard) has been pressed on Swift. Any ideas and suggestions will be greatly appreciated.

Answer

Since you updated your question and you wanted to know how to do this for a window, here's an answer. Subclass NSWindow and use this subclass instead.

Your custom class should look like this:

import Cocoa

class EditorWindow: NSWindow {
    override func keyDown(event: NSEvent) {
        super.keyDown(event)
        print("Caught a key down: \(event.keyCode)!")
    }
}

If you've made your window in Interface Builder/XCode, click the window object and go to the Attribute Inspector (++3). The Attribute Inspector will be in the sidebar on the right. Making sure your window is selected in Interface Builder, at the top of the Attribute Inspector in the Custom Class area put your new class in the class input.

Attribute Selector

Comments