Best strategy in swift to detect keyboad input in NSViewController

1k views Asked by At

I want to detect keyboard input in my NSViewController. The idea is to have several actions performed if the user presses certain keys followed by ENTER/RETURN.

I have checked if keyDown would be a appropriate way. But I would receive an event any time the user has pressed a key.

I also have though on using an NSTextField, set it to hidden and let it have the focus. But maybe there are other better solution.

Any ideas?

Thanks

1

There are 1 answers

0
Oliver Koehler On

I've finally got a solution that I like. First it has nothing todo with any hidden UI Elements but rather let the viewcontroller detect keyboard input.

var monitor: Any?
var text = ""
override func viewDidLoad() {
    super.viewDidLoad()
    self.monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown, handler: myKeyDownEvent)
}

override func viewWillDisappear() {
    //Clean up in case your ViewController can be closed an reopened
    if let monitor = self.monitor {
        NSEvent.removeMonitor(monitor)
    }
}

// Detect each keyboard event
func myKeyDownEvent(event: NSEvent) -> NSEvent {
    // keyCode 36 is for detect RETURN/ENTER
    if event.keyCode == 36 {
       print(text)
       text = ""
    } else {
       text.append( event.characters! )
    }
    return event
}