【问题标题】:Swift OSX key eventSwift OSX 按键事件
【发布时间】:2015-01-18 17:20:34
【问题描述】:

我一直在快速开发一个 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



}

}

【问题讨论】:

  • 阅读 Apple 指南,尤其是这个developer.apple.com/library/mac/documentation/Cocoa/Conceptual/…“处理关键事件”。您还将在其中找到示例代码。
  • 您不应该在该课程中使用该事件。在你的窗口类中使用它。
  • @Kendel 抱歉,但如果我只有 AppDelegate,没有 windows 类(它是一个菜单栏应用程序),我可以将覆盖函数放在哪里?

标签: macos cocoa swift keydown


【解决方案1】:

下面是一些示例代码:

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

    }

关键代码:

【讨论】:

  • 当我使用该示例代码时,我得到一个编译器错误,说它不能覆盖超类中的方法。我已经导入了 AppKit。我将在哪里使用上面的示例代码来接受键盘输入。谢谢
  • 我只是拼凑了一个测试项目并将其添加到初始化应用程序函数中。当我按下一个键时,当不接受键输入时,它会在我的 mac 上发出“boing 声音”。
  • 我以为你遇到了编译器错误?那么现在的问题是什么?
  • 我仍然得到编译器错误。它不会使用“覆盖”运行编译。我删除了覆盖,然后运行它并得到了这些结果。
  • 你能用你正在使用的代码编辑 OP。请全班。
【解决方案2】:
 override func keyDown(with event: NSEvent) {
    if (event.keyCode == 1){
        //do whatever when the s key is pressed
        print("S key pressed")
    }
}

为 SWIFT 3 更新

【讨论】:

    【解决方案3】:

    SWIFT 4:我创建了一个代码库来解决我的游戏中的这个问题。我主要将它与我的 MTKView 一起使用,但也应该与 NSViews 一起使用。

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

    【讨论】:

    • 这太棒了 - 它可以使用它来拦截键盘输入并过滤发送到 ViewController 中的文本字段的内容?
    猜你喜欢
    • 2018-02-27
    • 1970-01-01
    • 2011-04-24
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    相关资源
    最近更新 更多