Swift OSX key event

2019-02-02 17:00发布

问题:

I have been working on a Cocoa OSX project in swift that requires the use of keyboard input to preform an action. On keydown i want to move an object across the window, but stop the object as soon as the key is let up. I have looked in the documentation for AppKit and found the KeyDown function but I cannot seem to figure out how to use it. I want to create a function to call in my game update timer that will preform this. Thanks

import Cocoa
import Appkit

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

@IBOutlet weak var window: NSWindow!

func applicationDidFinishLaunching(aNotification: NSNotification) {
    // Insert code here to initialize your application

     func keyDown(theEvent: NSEvent) {
        if (theEvent.keyCode == 1){
            println("test")
        }

    }

}

func applicationWillTerminate(aNotification: NSNotification) {
    // Insert code here to tear down your application



}

}

回答1:

Here is some example code:

  override func keyDown(theEvent: NSEvent) {
            if (theEvent.keyCode == 1){
           //do whatever when the s key is pressed
        } 

    }

Key codes:



回答2:

 override func keyDown(with event: NSEvent) {
    if (event.keyCode == 1){
        //do whatever when the s key is pressed
        print("S key pressed")
    }
}

Updated for SWIFT 3



回答3:

SWIFT 4: I created a repo solving this problem on my games. Follow the readme and boom :) I mainly use this with my MTKView but should work with NSViews too.

https://github.com/twohyjr/NSView-Keyboard-and-Mouse-Input