How to find if the mouse is over a view

Arlen Anderson picture Arlen Anderson · Jan 7, 2011 · Viewed 11.8k times · Source

I need to find if the mouse position is inside an NSView's rect.

I'd use NSPointInRect(point, rect), but I'd need to convert the rect coordinates to screen coordinates and I'm not sure how. Any help would be much appreciated!

Answer

Jon Steinmetz picture Jon Steinmetz · Jan 7, 2011

Something like this should work for you:

NSView* myView; // The view you are converting coordinates to
NSPoint globalLocation = [ NSEvent mouseLocation ];
NSPoint windowLocation = [ [ myView window ] convertScreenToBase: globalLocation ];
NSPoint viewLocation = [ myView convertPoint: windowLocation fromView: nil ];
if( NSPointInRect( viewLocation, [ myView bounds ] ) ) {
    // Do your thing here
}

I don't personally use this many local variables but hopefully this make this example clearer.