macos - NSTrackingArea调用自定义代码

标签 macos cocoa nstrackingarea

当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仅定义对鼠标移动敏感的区域。为了回应他们,您需要:

  1. 使用 addTrackingArea: 方法将跟踪区域添加到您要跟踪的 View 。
  2. 可以根据您的需要在 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/

相关文章:

objective-c - NSTableView 中用于打开文件的按钮

macos - 如何在MacOS上安装Powershell

macos - 尝试横向扩展 Vert.x 服务器时出现 "Connection reset by peer"和 "Too many open files"异常

python - Django 教程 : runserver error

macos - 如何获得驱动器已开机的通知?

cursor - 将光标设置为指向 TextView 上的指针

macos - mac os x - sem_open 返回 errno 0,未定义错误

cocoa - 如何从 NSScriptCommand 子类的 PerformDefaultImplementation 返回对象列表?

objective-c - 禁用 NSView mousedown

objective-c - 当光标悬停在 NSTextView 内的 NSButton 上时,如何强制光标为 "arrowCursor"?