0

I have a very basic OS X that has a few different elements.

A text field, a table view and a file contents view.

I have a single ViewController.

I'd like to be able to intercept specific key events for each of these elements in the storyboard in my ViewController and change the focus between the different elements.

For example, if the cursor is currently in the file contents view, and I hit ESCAPE, I'd like for the focus to be transferred to the text field.

Or, if the focus is currently on the table view and I hit ENTER, that the cursor/focus is moved to the file contents view.

What's the best way to handle this?

I have tried overriding the keyDown method in the ViewController but with things such as autocomplete getting in the way, I'm not having much luck. I have added a print statement to keyDown to check if the function is receiving events, but it's not always fired.

Update

Except for the specific keys that I want to intercept, I want all other key events to behave as normal. For example, typing in the file contents view, or the text field.

0

1 Answer 1

0

I would highly recommend watching the WWDC talk #145 from 2010, Key Event Handling in Cocoa Applications. It gives an overview of the event delivery mechanism, and several ways of handling events:

  • Make a menu item or button whose keyEquivalent is the escape key.

  • Override cancelOperation(_:) or complete(_:), which are the two NSResponder methods which can get invoked by default when the escape key is pressed. (There are other methods for the enter/return key.)

  • Override sendEvent(_:) in NSApplication or NSWindow to intercept all events and bypass the default behavior.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.