开发者

How to use NSTrackingArea

I'm new to Mac programming and I want to fire events when the cursor enters or exits the main window. I r开发者_运维知识库ead something about NSTrackingArea but I don't understand exactly what to do.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜