为了账号安全,请及时绑定邮箱和手机立即绑定

Swift-从NSViewController捕获keydown

Swift-从NSViewController捕获keydown

繁星coding 2019-11-29 10:36:00
我想在我的小应用程序中捕获关键事件。我做了什么:class ViewController : NSViewController {...  override func keyDown(theEvent: NSEvent) {        if theEvent.keyCode == 124 {            println("abc")        } else {            println("abcd")        }    }    override var acceptsFirstResponder: Bool {        return true    }    override func becomeFirstResponder() -> Bool {        return true    }    override func resignFirstResponder() -> Bool {        return true    }...}怎么了:按下键时,会播放Funk声音效果。我看过很多帖子在谈论如何,这是一个代表了属于NSView和NSViewController不具有访问权限。但是keydown函数override自动完成的类类型使NSViewController我相信这是错误的。
查看完整描述

3 回答

?
月关宝盒

TA贡献1772条经验 获得超5个赞

迅捷4


刚刚找到了针对同一问题的解决方案Swift4。其背后的思想是:如果按下的键是由自定义逻辑处理的,则处理程序应返回nil,否则返回(未处理的)事件...


class MyViewController: NSViewController {

   override func viewDidLoad() {

      super.viewDidLoad()

      // ...

      NSEvent.addLocalMonitorForEvents(matching: .keyDown) {

         if self.myKeyDown(with: $0) {

            return nil

         } else {

            return $0

         }

      }

   }

   func myKeyDown(with event: NSEvent) -> Bool {

      // handle keyDown only if current window has focus, i.e. is keyWindow

      guard let locWindow = self.view.window,

         NSApplication.shared.keyWindow === locWindow else { return false }

      switch Int( event.keyCode) {

      case kVK_Escape:

         // do what you want to do at "Escape"

         return true

      default: 

         return false

      }

   }

}

我们在这里:按下键时没有发出Purr / Funk声音...


[更新]添加了对keyWindow的检查。没有这个,即使另一个视图/窗口包含第一个响应者,也会触发keyDown()。


查看完整回答
反对 回复 2019-11-29
?
holdtom

TA贡献1805条经验 获得超10个赞

我正在尝试为swift 3找到答案,这对我有用:


迅捷3

import Cocoa


// We subclass an NSView


class MainView: NSView {


    // Allow view to receive keypress (remove the purr sound)

    override var acceptsFirstResponder : Bool {

        return true

    }


    // Override the NSView keydown func to read keycode of pressed key

    override func keyDown(with theEvent: NSEvent) {

        Swift.print(theEvent.keyCode)

    }


查看完整回答
反对 回复 2019-11-29
  • 3 回答
  • 0 关注
  • 766 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信