当NSTrackingArea定义的区域捕获鼠标事件时,如何调用自己的方法?我可以在 NSTrackingArea init 中指定我自己的方法(例如“myMethod”)吗?
trackingAreaTop = [[NSTrackingArea alloc] initWithRect:NSMakeRect(0,0,100,100) options:(NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveAlways) owner:myMethod userInfo:nil];
谢谢!
最佳答案
Can I specify my own method (e.g. "myMethod") in the NSTrackingArea init as below?
trackingAreaTop = [[NSTrackingArea alloc] initWithRect:NSMakeRect(0,0,100,100) options:(NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveAlways) owner:myMethod userInfo:nil];
没有。所有者应该是接收请求的鼠标跟踪、鼠标移动或光标更新消息的对象,而不是方法。如果您传入自定义方法,它甚至不会编译。
How can I call my own method when the area defined by NSTrackingArea captures mouse events?
NSTrackingArea
仅定义对鼠标移动敏感的区域。为了回应他们,您需要:
- 使用
addTrackingArea:
方法将跟踪区域添加到您要跟踪的 View 。 - 可以根据您的需要在
owner
类中实现mouseEntered:
、mouseMoved:
或mouseExited:
方法需要。
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:frame options:NSTrackingMouseEnteredAndExited owner:self userInfo:nil];
[self addTrackingArea:trackingArea];
}
return self;
}
- (void)mouseEntered:(NSEvent *)theEvent {
NSPoint mousePoint = [self convertPoint:[theEvent locationInWindow] fromView:nil];
// do what you desire
}
详情请参阅Using Tracking-Area Objects .
<小时/>顺便说一句,如果您想响应鼠标单击事件而不是鼠标移动事件,则无需使用 NSTrackingArea
。只需继续实现 mouseDown:
或 mouseUp:
方法即可。
关于macos - NSTrackingArea调用自定义代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30289921/