NSTrackingArea 调用自定义代码

NSTrackingArea call custom code

NSTrackingArea定义的区域捕获鼠标事件时,如何调用自己的方法?我可以在 NSTrackingArea 初始化中指定我自己的方法(例如 "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];

没有。 owner 应该是一个对象来接收请求的鼠标跟踪、鼠标移动或光标更新消息,而不是方法。如果您传入自定义方法,它甚至不会编译。

How can I call my own method when the area defined by NSTrackingArea captures mouse events?

NSTrackingArea只定义对鼠标移动敏感的区域。为了回复他们,您需要:

  1. 使用 addTrackingArea: 方法将您的跟踪区域添加到要跟踪的视图。
  2. 可选择根据需要在 owner class 中实施 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: 方法即可。