Swift OSX key event

2019-02-02 17:23发布

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



}

}

3条回答
一夜七次
2楼-- · 2019-02-02 17:50

Here is some example code:

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

    }

Key codes: enter image description here

查看更多
Emotional °昔
3楼-- · 2019-02-02 17:52

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

查看更多
神经病院院长
4楼-- · 2019-02-02 17:53
 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

查看更多
登录 后发表回答