Responding to Events in an NSView

In addition to drawing, the NSView class can also process events (because it’s a subclass of the NSResponder abstract superclass). To receive mouse-down or mouse-up events, all your custom NSView needs to do is override one of the following event-handling methods (there are others) that are declared in the NSResponder class:

- (void)mouseDown:(NSEvent *)theEvent
- (void)rightMouseDown:(NSEvent *)theEvent
- (void)mouseUp:(NSEvent *)theEvent
- (void)rightMouseUp:(NSEvent *)theEvent
- (void)mouseDragged:(NSEvent *)theEvent
- (void)rightMouseDragged:(NSEvent *)theEvent

To receive mouse-entered or mouse-exited events, your custom NSView needs to override one of the following event methods and set up a tracking rectangle — something we will describe later, in Chapter 18.

- (void)mouseEntered:(NSEvent *)theEvent
- (void)mouseExited:(NSEvent *)theEvent

Additionally, if your custom NSView is made the first responder of its containing window, it will receive the following keyboard and mouse events:

- (void)keyDown:(NSEvent *)theEvent
- (void)keyUp:(NSEvent *)theEvent
- (void)mouseMoved:(NSEvent *)theEvent

Tip

mouseMoved: events must be turned on explicitly. We will discuss this topic in Chapter 18.

In the remainder of this section, we’ll show you how to receive and interpret mouse-related events and how to detect whether or not a point is within a polygon.

Getting a Mouse-Down Event

Overriding an event method can be as simple as adding a single method to your ...

Get Building Cocoa Applications: A Step by Step Guide 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.