O'Reilly logo

Beginning Mac OS® X Programming by Drew McCormack, Michael Trent

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required