Feb 262014
 

In some case we want to track mouse movement in table view cell. This can be done by subclassing the NSTableViewCell if the table is view type class.

The idea in this example is to show ‘Order fruit’ button only when the mouse is move into the fruit cell. Code below how this is done by subclassing NSTableViewCell.


@implementation WLFruitCellView
{
    NSTrackingArea *_trackingArea;
}

- (void)awakeFromNib{
    [self createTrackingArea];
    
    //hide the button first
    [self.eatButton setHidden:YES];
}


/**
 Create tracking area when mouse move in
 */
- (void)createTrackingArea
{
    _trackingArea = [[NSTrackingArea alloc] initWithRect:self.bounds options:NSTrackingMouseEnteredAndExited|NSTrackingActiveInActiveApp owner:self userInfo:nil];
    [self addTrackingArea:_trackingArea];
    
    NSPoint mouseLocation = [[self window] mouseLocationOutsideOfEventStream];
    mouseLocation = [self convertPoint: mouseLocation
                              fromView: nil];
    
    if (NSPointInRect(mouseLocation, [self bounds]))
    {
        [self mouseEntered: nil];
    }
    else
    {
        [self mouseExited: nil];
    }
}

- (void)drawRect:(NSRect)dirtyRect
{
	[super drawRect:dirtyRect];
	
    // Drawing code here.
}

- (void)mouseEntered:(NSEvent *)theEvent{
    
    self.eatButton.title = [NSString stringWithFormat:@"Order %@", self.textField.stringValue];
    [self.eatButton setHidden:NO];
    NSLog(@"Entered '%@'", self.textField.stringValue);
}

- (void)mouseExited:(NSEvent *)theEvent{
    [self.eatButton setHidden:YES];
    NSLog(@"Exited '%@'", self.textField.stringValue);
}

Below is example project for tracking mouse in NSTableView or NSOutlineView, the method is same which is subclass NSTableViewCell. In this project binding is used for displaying fruits content.