Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use NSTrackingArea

Tags:

macos

cocoa

I'm new to Mac programming and I want to fire events when the cursor enters or exits the main window. I read something about NSTrackingArea but I don't understand exactly what to do.

like image 717
icant Avatar asked Jan 09 '11 13:01

icant


2 Answers

Apple provides documentation and examples for NSTrackingAreas.

The easiest way to track when a mouse enters or exits a window is by setting a tracking area in the window's contentView. This will however not track the window's toolbar

Just as a quick example, in the custom content view's code:

- (void) viewWillMoveToWindow:(NSWindow *)newWindow {
    // Setup a new tracking area when the view is added to the window.
    NSTrackingArea* trackingArea = [[NSTrackingArea alloc] initWithRect:[self bounds] options: (NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways) owner:self userInfo:nil];
    [self addTrackingArea:trackingArea];
}

- (void) mouseEntered:(NSEvent*)theEvent {
    // Mouse entered tracking area.
}

- (void) mouseExited:(NSEvent*)theEvent {
    // Mouse exited tracking area.
}

You should also implement NSView's updateTrackingAreas method and test the event's tracking area to make sure it is the right one.

like image 99
Matt Bierner Avatar answered Nov 18 '22 09:11

Matt Bierner


Answer by Matt Bierner really helped me out; needing to implement -viewWillMoveToWindow: method.

I would also add that you will also need to implement this if you want to handle tracking areas when the view is resized:

- (void)updateTrackingAreas
{
   // remove out-of-date tracking areas and add recomputed ones..
}

in the custom sub-class, to handle the view's changing geometry; this'll be invoked for you automatically.

like image 29
petert Avatar answered Nov 18 '22 10:11

petert