4

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.

NSGod
  • 22,699
  • 3
  • 58
  • 66

2 Answers2

1

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.

Jakob Egger
  • 11,981
  • 4
  • 38
  • 48
0

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);
}
rdelmar
  • 103,982
  • 12
  • 207
  • 218
  • As long as the questioner just wants to show a contextual menu, wouldn't overriding `menuForEvent:` be more proper? – Peter Hosey Mar 10 '13 at 10:36
  • rdelmar, this is exactly what I was looking for - thank you. However, when I subclass my NSTableHeaderView no column titles show up at run time (they show up at design time though). – Eric Hartner Mar 12 '13 at 23:51