365Cocoa

A snippet of Objective-C code per day, 365 days long.
Written by Pieter Omvlee, developer and owner of Bohemian Coding.

Apr 15

Day 43: NSView event handling 1; mouseMoved

Custom view programming often involves two distinct kind of operations; drawing and event handling. I have already given a few examples of drawing stuff in NSViews and today I’ll start with some examples of handing events.

Mouse events enter your view in four different methods; mouseDown, mouseDragged, mouseUp and optionally mouseMoved. To accept mouseMoved events, you’ll have to tell the window that you’re interested in them.

  [[self window] setAcceptsMouseMovedEvents:YES];

Note that the view only receives mouseMovedEvents if the view is the first responder. So make sure you override this and return YES:
- (BOOL)acceptsFirstResponder{  return YES;}
This is a question of comes up in forums so I hope this has been useful to at least a few people. Tomorrow I’ll show how to get the location of the mouse inside your view.

  1. lsi17klas reblogged this from 365cocoa
  2. 365cocoa posted this