[英]Swift OSX key event
I have been working on a Cocoa OSX project in swift that requires the use of keyboard input to preform an action. 我一直在使用swift中的Cocoa OSX项目,需要使用键盘输入来执行操作。 On keydown i want to move an object across the window, but stop the object as soon as the key is let up.
在keydown上我想在窗口上移动一个对象,但是一旦关键松开就停止对象。 I have looked in the documentation for AppKit and found the KeyDown function but I cannot seem to figure out how to use it.
我查看了AppKit的文档并找到了KeyDown函数,但我似乎无法弄清楚如何使用它。 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
}
} }
Here is some example code: 这是一些示例代码:
override func keyDown(theEvent: NSEvent) {
if (theEvent.keyCode == 1){
//do whatever when the s key is pressed
}
}
Key codes: 关键代码:
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 针对SWIFT 3进行了更新
SWIFT 4: I created a repo solving this problem on my games. SWIFT 4:我在游戏中创建了一个解决此问题的仓库。 I mainly use this with my MTKView but should work with NSViews too.
我主要在我的MTKView上使用它,但也应该使用NSViews。
https://github.com/twohyjr/NSView-Keyboard-and-Mouse-Input https://github.com/twohyjr/NSView-Keyboard-and-Mouse-Input
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.