How to handle mouse events in OS X

Handling mouse events in OS X is very different from the way in which we’re used to dealing with touch events in iOS. Here’s how to do it:

You must subclass an NSView and assign your class in the the xib file – much like you would subclass a UIViewController and assign your own in the storyboard. Every Cocoa Application has at least one view, found under the Window of your app (you may have to expand the Document Outline for this to show, it’s at the bottom left in Interface Builder):

Screen Shot 2014-04-16 at 08.16.19

Then in your own class you can track mouse events by implementing these functions among several others:

// react to mouse events
- (void)mouseDown:(NSEvent *)theEvent {
    NSLog(@"Mouse was clicked");

- (void)mouseDragged:(NSEvent *)theEvent {
    NSLog(@"Mouse is dragging");

- (void)mouseUp:(NSEvent *)theEvent {
    NSLog(@"Mouse was let go");

The Apple documentation also mentions that we should override the following method for our custom view to accept mouse events – but in OS X 10.9.2 I didn’t find this to make a difference:

- (BOOL)acceptsFirstResponder {
    return YES;

First Mouse Event

There is something called the “first mouse” event. This is called when an app or window not currently in focus is clicked on. Usually that window will ignore where you clicked and only bring the app or window into focus, and then reacts to mouse events.

You can change this behaviour by overriding the following method:

// accept first mouse events
- (BOOL)acceptsFirstMouse:(NSEvent *)theEvent {
    NSLog(@"Got first mouse event");
    return YES;

Leave a Reply