Swift OSX关键事件

the*_*r61 8 macos cocoa keydown swift

我一直在使用swift中的Cocoa OSX项目,需要使用键盘输入来执行操作.在keydown上我想在窗口上移动一个对象,但是一旦关键松开就停止对象.我查看了AppKit的文档并找到了KeyDown函数,但我似乎无法弄清楚如何使用它.我想在我的游戏更新计时器中创建一个函数来调用它.谢谢

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



}
Run Code Online (Sandbox Code Playgroud)

}

Ken*_*del 18

这是一些示例代码:

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

    }
Run Code Online (Sandbox Code Playgroud)

关键代码: 在此输入图像描述


cle*_*001 5

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

已为SWIFT 3更新