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):

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

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.