Re: Key event handling theory
Re: Key event handling theory
- Subject: Re: Key event handling theory
- From: Greg Titus <email@hidden>
- Date: Fri, 4 Jan 2002 13:12:43 -0800
On Friday, January 4, 2002, at 12:46 PM, Brian Webster wrote:
I'm trying to get a handle on what the intended design patterns are in
Cocoa when it comes to handling key down events. That is, I'd like to
know what way people think is "best" for dispatching keypresses in
custom views. A simple example would be having a table view that
allows the user to press delete to delete the selected rows, or other
additions like that.
The way that seems along the right tracks is to override the keyDown:
method in your view and then pass the event along to
interpretKeyEvents:. You would then just have to bind whatever keys
you want to the appropriate selectors and they will just get called
automatically. However, I can't figure out how to go about the binding
process, since it seems to me that key binding affects the whole app,
and not just one view class or instance. It also seems like most of
the binding stuff is geared towards text views specifically, so I don't
know if it's meant to be used for non-text views.
NSResponder already implements -keyDown: to pass along the key events to
-interpretKeyEvents: so all of that is basically done for you. To
implement your simple example, all you really have to do is implement a
method called -deleteBackwards:.
The NSResponder machinery will:
1) In -keyDown: pass the event to -interpretKeyEvents:
2) In -interpretKeyEvents: it will do the binding to the deleteBackwards
command and call -doCommandBySelector:
3) In -doCommandBySelector: the default implementation just sees if self
responds to the selector and calls it so
4) Your -deleteBackwards: method is invoked.
The way I'd recommend hooking into this is:
* If there is already a command for the keyboard event you are
interested in (like in this example) just implement the command method
(-deleteBackwards:) and leave everything else alone.
* Only override -doCommandBySelector: if you want to add your own
'chain' of possible handlers, like NSTextView calls its delegate with
-textView:doCommandBySelector:.
* Only override -interpretKeyEvents: if you have some other key that you
want to do something special that isn't currently defined (for example,
making control-alt-tilde be the -frob: command)
* Only override -keyDown: directly if you want to handle typing instead
of key commands (if you see what I mean...). Be sure to call the
superclass implementation for any key that you don't explicitly handle
so the rest of the machinery still happens.
Hope this helps,
--Greg