Skip to content

Instantly share code, notes, and snippets.

@Rm1210
Last active August 29, 2015 14:11
Show Gist options
  • Save Rm1210/973a934cdba1deb61d9c to your computer and use it in GitHub Desktop.
Save Rm1210/973a934cdba1deb61d9c to your computer and use it in GitHub Desktop.
#import <Cocoa/Cocoa.h>
@protocol ContextMenuDelegate <NSObject>
- (NSMenu*)tableView:(NSTableView*)aTableView menuForRows:(NSIndexSet*)rows;
@end
@interface NSTableView (ContextMenu)
@end
----------
@implementation NSTableView (ContextMenu)
- (NSMenu*)menuForEvent:(NSEvent*)event
{
NSPoint location = [self convertPoint:[event locationInWindow] fromView:nil];
NSInteger row = [self rowAtPoint:location];
if (!(row >= 0) || ([event type] != NSRightMouseDown)) {
return [super menuForEvent:event];
}
NSIndexSet *selected = [self selectedRowIndexes];
if (![selected containsIndex:row]) {
selected = [NSIndexSet indexSetWithIndex:row];
[self selectRowIndexes:selected byExtendingSelection:NO];
}
if ([[self delegate] respondsToSelector:@selector(tableView:menuForRows:)]) {
return [(id)[self delegate] tableView:self menuForRows:selected];
}
return [super menuForEvent:event];
}
@end
@Rm1210
Copy link
Author

Rm1210 commented Dec 18, 2014

This category adds functionality to NSTableView that should have been there in the first place: contextual (right click) menus. Usage is simple:

  1. Add the category to your project
  2. Make sure that the NSTableView's delegate outlet is connected
  3. Implement the ContextMenuDelegate protocol in your controller and return the NSMenu that you want to display

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment