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.

  4 Responses to “Track Mouse Movement in NSTableViewCell”

  1. Thanks, this post is very helpful. You saved my hours!

  2. […] 훑어 보시면 이해할 수 있으시리라 생각합니다. 도움을 준 원본 포스트는 이곳입니다. 그곳으로 이동하시면 아래 예제코드를 다운로드 하실 수 […]

  3. Thank you so much for this! I have spent hours trying to solve this problem. Your example is missing the following piece of code to work properly though, but you put me on the right track:

    – (void)updateTrackingAreas{
    [self removeTrackingArea:_trackingArea];
    _trackingArea = nil;
    [self createTrackingArea];
    }

    Without this piece, I only got one message when I started the program no matter how much I moved my mouse pointer over the table cell.

Leave a Reply