Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if the mouse is over a view

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!

like image 509
Arlen Anderson Avatar asked Jan 07 '11 21:01

Arlen Anderson


4 Answers

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.

like image 57
Jon Steinmetz Avatar answered Nov 01 '22 16:11

Jon Steinmetz


Use NSView's convertPoint:fromView: method with fromView as nil to covert a point in window coordinates to a view's coordinate system.

After converting the mouse point to the view's coordinate system, I would use NSView's mouse:inRect: method instead of NSPointInRect as the former also accounts for flipped coordinate systems.

Alternatively, you could use a Tracking Area Object.

like image 24
Matt Bierner Avatar answered Nov 01 '22 18:11

Matt Bierner


The NSView isMousePoint function works for me, without having to worry about anything CG.

func isMouseInView(view: NSView) -> Bool? {
    if let window = view.window {
        return view.isMousePoint(window.mouseLocationOutsideOfEventStream, in: view.frame)
    }
    return nil
}
like image 7
Ryan H Avatar answered Nov 01 '22 16:11

Ryan H


Some code making use of mouse:inRect: (the recommended way; that accounts for flipped coordinates)

CGPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
CGRect rect = [self bounds];
if ([self mouse:point inRect:rect]) {
}
like image 5
aepryus Avatar answered Nov 01 '22 18:11

aepryus