macos 如何使用 NSTrackingArea

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4639379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 07:34:54  来源:igfitidea点击:

How to use NSTrackingArea

cocoamacos

提问by icant

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.

我是 Mac 编程的新手,我想在光标进入或退出主窗口时触发事件。我读了一些关于 NSTrackingArea 的内容,但我不明白该怎么做。

回答by Matt Bierner

Apple provides documentation and examples for NSTrackingAreas.

Apple 为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

跟踪鼠标何时进入或退出窗口的最简单方法是在窗口的 contentView 中设置跟踪区域。然而,这不会跟踪窗口的工具栏

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 updateTrackingAreasmethod and test the event's tracking area to make sure it is the right one.

您还应该实现 NSView 的updateTrackingAreas方法并测试事件的跟踪区域以确保它是正确的。

回答by petert

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

Matt Bierner 的回答真的帮了我大忙;需要实现-viewWillMoveToWindow:方法。

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.

在自定义子类中,处理视图的几何变化;这将自动为您调用。