Mouse moved events during button mouse up event

Viewed 143

I want to receive information about mouse move events during button click (mouse up)

I'm adding NSTrackingArea to view that I want to track mouse move and mouse dragged events on, but I still don't receive these events.

I assume that mouseDown in NSButton is blocking mouse events, so the only solution I come up with is overriding mouseDown function for NSButton and not calling super.mouseDown, but then I need to handle button selection manually and I'm not sure if this is right approach for this.

Is this a right solution for my problem? Will there be no problems? Is there a better solution?

Here is code for test, just add button to new project and assign TestButton class to it.

class TestButton: NSButton {

    override func mouseDown(with event: NSEvent) {
        print("Mouse up")
        super.mouseDown(with: event) // After removing events works.
        print("Mouse down")
    }
}

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let trackingArea = NSTrackingArea(rect: view.bounds, options: [.activeAlways, .mouseMoved, .enabledDuringMouseDrag], owner: self, userInfo: nil)
        view.addTrackingArea(trackingArea)
    }

    override func mouseMoved(with event: NSEvent) {
        print("Mouse moved")
        super.mouseMoved(with: event)
    }

    override func mouseDragged(with event: NSEvent) {
        print("Mouse dragged")
        super.mouseDragged(with: event)
    }
}
2 Answers

I had a similar requirement for my project. So initially, I started out with NSButton just like you. But, it turned out to be more hectic than I thought. Handling the action and selected state where the main concerns I faced. You could proceed with NSButton if it actually meets up with your requirement. But, I eventually moved to NSView and customised it. So, few of my implementation for handling move and drag event implementation I've open-sourced here is the link.

The traditional way to do this is to use a custom subclass of NSButtonCell and override continueTracking(last:current:in:) (inherited from NSCell). Your override should generally call through to super and return what it returns, but you can do something else in addition, to respond to the mouse movements. The issue is that NSCell and its subclasses have been "soft deprecated" for a while.

That said, it would be very surprising to me as a user that anything other than the button would react to the mouse movements while I'm interacting with the button (clicked in it and dragging).

Related