macosmousedownnsevent

Getting [NSEvent mouseLocation] in view coordination system


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.


Solution

  • 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];