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()。
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)
}
- 3 回答
- 0 关注
- 848 浏览
添加回答
举报