Search code examples
swiftmouseeventframenseventnspoint

Prove if cursors location is within NSButton’s frame


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!


Solution

  • 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)