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:

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:

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:

About Jay Versluis

Jay is a medical miracle known as Super Survivor. He runs two YouTube channels, five websites and several podcast feeds. To see what else he's up to, and to support him on his mission to make the world a better place, check out his Patreon Campaign.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.