Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mouseMoved not called

I have a subclassed NSView which is part of a .xib-file of a subclassed NSDocument, which gets alive by the default behaviour of NSDocumentController's openDocument: method. In this subclassed NSView I have implemented the methods awakeFromNib, in which the view's NSWindow setAcceptsMouseMovedEvents:YES method is called, and acceptsFirstMouse:, which returns YES. But my mouseMoved: method implementation of my subclassed NSView doesn't get called when I move the mouse over it. What might be the problem?

like image 338
Dominik Seibold Avatar asked Sep 25 '11 04:09

Dominik Seibold


3 Answers

Be sure to request the mouseMoved event is sent:

NSTrackingAreaOptions options = (NSTrackingActiveAlways | NSTrackingInVisibleRect |  
                         NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved);

NSTrackingArea *area = [[NSTrackingArea alloc] initWithRect:[self bounds]
                                                    options:options
                                                      owner:self
                                                   userInfo:nil];
like image 77
zeeple Avatar answered Oct 24 '22 07:10

zeeple


As noted by others, an NSTrackingArea is a good solution, and an appropriate place to install the tracking area is NSView.updateTrackingAreas(). It isn't necessary to set the containing NSWindow's setAcceptsMouseMovedEvents property.

In Swift 3:

class CustomView : NSView {

    var trackingArea : NSTrackingArea?

    override func updateTrackingAreas() {
        if trackingArea != nil {
            self.removeTrackingArea(trackingArea!)
        }
        let options : NSTrackingAreaOptions =
            [.mouseEnteredAndExited, .mouseMoved, .activeInKeyWindow]
        trackingArea = NSTrackingArea(rect: self.bounds, options: options,
                                      owner: self, userInfo: nil)
        self.addTrackingArea(trackingArea!)
    }

    override func mouseMoved(with event: NSEvent) {
        Swift.print("Mouse moved: \(event)")
    }
}
like image 28
jbouwman Avatar answered Oct 24 '22 07:10

jbouwman


I haven't used mouseMoved: in a real project (I've just played around with it a little). As far as I can tell, mouseMoved: is only called when your view is the first responder and then not only while the mouse is over your view, but always when the mouse moves. You might be better off using an NSTrackingArea. Check the Cocoa Event Handling Guide for more information.

like image 13
Michael Avatar answered Oct 24 '22 08:10

Michael