Prove if cursors location is within NSButton’s frame

386 views Asked by At

I have a custom NSButton class and want to check (within viewWillDraw) if the users current mouse location is inside the buttons frame.

I get the mouse position using NSEvent.mouseLocation(), but that gives me an absolute NSPoint in relation to the screen itself.

self.frame (= NSButton.frame) instead returns some relative coordinates, refering to the buttons superview.

As a result, self.frame.contains(NSEvent.mouseLocation()) does not work and I have no idea how to solve that!

Appreciate any help!

1

There are 1 answers

2
Vitaly Migunov On BEST ANSWER

You can add NSTrackingArea with NSTrackingAreaOptions.MouseEnteredAndExited to your Button

Or you can use this code

Convert NSPoint to superview's coordinate system

let point = self.superview!.convert(self.window!.mouseLocationOutsideOfEventStream, from: nil)

And then just use self.frame.contains

if self.frame.contains(point)