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 關注
- 893 瀏覽
添加回答
舉報