365Cocoa

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

Apr 16

Day 43: NSView event handling 2; mouse coordinates

Intercepting mouse clicks is easy enough, you just have to override mouseDown:. However correctly getting the location of the cursor inside your view is less straightforward.

NSView has a bunch of method for converting points from one view/window’s coordinate system to another but I find them very confusingly named. I can never remember the one I need. I basically always end up copying/pasting the method call from a previous project:

- (NSPoint)mouseEventToPoint:(NSEvent *)anEvent
{
  NSPoint mouse = [self convertPoint:[anEvent locationInWindow] fromView:nil];
}