Swift OSX key event

為{幸葍}努か 提交于 2019-12-30 01:19:07

问题


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. I mainly use this with my MTKView but should work with NSViews too.

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



来源:https://stackoverflow.com/questions/28012566/swift-osx-key-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!