8.12. Responding to Keyboard Events

Most Cocoa controls handle keyboard events automatically. For example, NSTextField controls automatically update their contents when you type, NSTableView objects will change their selection when you press the arrow keys, and so on. The responder chain routes events directly to these objects so you don't have to worry about event processing yourself. Sometimes you need to extend an object to handle a certain kind of event. For example, you might need to change a button's behavior when you Option-click it.

This is another case where subclassing an existing Cocoa control is a good solution to this problem. You just want to write the code specific to your situation, and inherit the rest of the control's behavior from its super class. Most of the time, your objects can simply pass the event farther down the responder chain, and handle the event in your NSWindowController subclass (or your window delegate, if you aren't using NSWindowController).

In the following Try It Out, you extend Slide Master's slide show document's image view to respond to keyboard events. For example, you delete the currently selected slides by pressing the Delete key. Pressing the arrow keys will also advance the selection, just like when the table view is selected. Because you are already using a custom NSImageView subclass, SlideImageView, you won't need to edit your nib files at all.

8.12.1.

8.12.1.1. Try It Out: Responding to Keyboard Events
  1. In Xcode, open SlideImageView.m ...

Get Beginning Mac OS® X Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.