Which Column Was Right Clicked In NSTableHeaderView

499 Views Asked by At

When I right click my table view header (NSTableHeaderView) I'm popping up a menu to allow the user to change the column color. The problem is that I don't know what column they just "right clicked" on. Any ideas on how to do this? Thank you.

2

There are 2 best solutions below

0
On

The easiest way to do this is to implement -menuForEvent: in a subclass of NSTableHeaderView.

In my app, I use a more general solution. I added a delegate to the NSTableHeaderView. When the menu is requested, my class asks the delegate to validate the menu and passes it the clicked table column. The delegate then customizes the menu (enables menu items, sets menu item state according to clicked column), and it remembers which column was clicked in an instance variable.

PGETableViewTableHeaderView.h

#import <Cocoa/Cocoa.h>

@protocol PGETableViewTableHeaderViewDelegate <NSObject>
-(void)validateMenu:(NSMenu*)menu forTableColumn:(NSTableColumn*)tableColumn;
@end

@interface PGETableViewTableHeaderView : NSTableHeaderView
@property(weak) IBOutlet id<PGETableViewTableHeaderViewDelegate> delegate;
@end

PGETableViewTableHeaderView.m

#import "PGETableViewTableHeaderView.h"

@implementation PGETableViewTableHeaderView
-(NSMenu *)menuForEvent:(NSEvent *)event {
    NSInteger clickedColumn = [self columnAtPoint:[self convertPoint:event.locationInWindow fromView:nil]];
    NSTableColumn *tableColumn = clickedColumn != -1 ? self.tableView.tableColumns[clickedColumn] : nil;
    NSMenu *menu = self.menu;
    [self.delegate validateMenu:menu forTableColumn:tableColumn];
    return menu;
}
@end

It's quite convenient: assign the custom subclass to the header view in IB, then hook up the menuand delegateoutlets.

2
On

One way to do this is to override rightMouseDown in a custom NSTableHeaderView class:

-(void)rightMouseDown:(NSEvent *)theEvent {
    NSPoint p = [self convertPoint:theEvent.locationInWindow fromView:nil];
    NSInteger selCol = [self columnAtPoint:p];
    NSLog(@"Clicked on header cell is in column: %ld",selCol);
}