macoscocoanstrackingarea

NSTrackingArea call custom code


How can I call my own method when the area defined by NSTrackingArea captures mouse events? 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];

Thanks!


Solution

  • 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];
    

    No. The owner is supposed to be an object to receive the requested mouse-tracking, mouse-moved, or cursor-update messages, not a method. It won't even compile if you pass in your custom method.

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

    NSTrackingArea only defines the area that is sensitive to the movements of the mouse. In order to respond to them, you need to:

    1. Add your tracking area to the view you want to track using the addTrackingArea: method.
    2. Optionally implement the mouseEntered:, mouseMoved: or mouseExited: methods in your owner class as per your need.

    - (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
    }
    

    For details, please refer to Using Tracking-Area Objects.


    As a aside, if you want to respond to mouse clicking events rather then mouse movement events, there is no need to use NSTrackingArea. Just go ahead and implement the mouseDown: or mouseUp: method instead.