Getting [NSEvent mouseLocation] in view coordination system

Niv picture Niv · May 21, 2014 · Viewed 8.5k times · Source

I have an NSView that is catching a mouseDown event.

I'm getting the coordination of the mouse click using:

- (void)mouseDown:(NSEvent *)theEvent {
    NSPoint touchPoint = [NSEvent mouseLocation];
    //Rest of code
}

However, this sets clickPoint as the location of the mouse in the global screen coordination.

I want to get the position of the click in the relative view coordination - If the user clicks in the bottom left corner of the window, I want the point to be (0, 0) no matter where the containing window is on the screen.

Answer

JWWalker picture JWWalker · May 21, 2014

You should be using locationInWindow, not mouseLocation. The docs on locationInWindow show how to go from there:

NSPoint event_location = [theEvent locationInWindow];
NSPoint local_point = [self convertPoint:event_location fromView:nil];