这是一个代表! - 不需要子类
在IB中,如果您将NSTableView
拖到窗口/视图上,您会注意到该表为一个menu
插座。
因此,为了实现上下文菜单非常容易的方式是到该出口处的菜单的委托出口连接到短截线的菜单,并连接到其实现NSMenuDelegate
协议方法- (void)menuNeedsUpdate:(NSMenu *)menu
对象通常,菜单的委托是提供数据源/委托给表的同一个对象,但它也可能是拥有该表的视图控制器。
Have a look at the docs查找有关此
更多信息即使世界的巧妙的东西捆你可以在协议做,但一个非常简单的实现可能会像下面
#pragma mark tableview menu delegates
- (void)menuNeedsUpdate:(NSMenu *)menu
{
NSInteger clickedrow = [mytable clickedRow];
NSInteger clickedcol = [mytable clickedColumn];
if (clickedrow > -1 && clickedcol > -1) {
//construct a menu based on column and row
NSMenu *newmenu = [self constructMenuForRow:clickedrow andColumn:clickedcol];
//strip all the existing stuff
[menu removeAllItems];
//then repopulate with the menu that you just created
NSArray *itemarr = [NSArray arrayWithArray:[newmenu itemArray]];
for(NSMenuItem *item in itemarr)
{
[newmenu removeItem:[item retain]];
[menu addItem:item];
[item release];
}
}
}
然后构建菜单的方法。
-(NSMenu *)constructMenuForRow:(int)row andColumn:(int)col
{
NSMenu *contextMenu = [[[NSMenu alloc] initWithTitle:@"Context"] autorelease];
NSString *title1 = [NSString stringWithFormat:@"Delete %@",[self titleForRow:row]];
NSMenuItem *item1 = [[[NSMenuItem alloc] initWithTitle:title1 action:@selector(deleteObject:) keyEquivalent:@""] autorelease];
[contextMenu addItem:item1];
//
NSString *title2 = [NSString stringWithFormat:@"Save %@",[self titleForColumn:col]];
NSMenuItem *item2 = [[[NSMenuItem alloc] initWithTitle:title1 action:@selector(saveObject:) keyEquivalent:@""] autorelease];
[contextMenu addItem:item2];
return contextMenu;
}
如何选择实现titleForRow:
和titleForColumn:
是你。
注意NSMenuItem
提供财产representedObject
允许你任意对象绑定到菜单项,从而将信息发送到您的方法(如deleteObject:
)
编辑
当心 - 实施- (void)menuNeedsUpdate:(NSMenu *)menu
在您的NSDocument
子类中将停止出现在10.8中出现的标题栏中的自动保存/版本菜单。
它仍然工作在10.7所以去图。在任何情况下,菜单代表将需要是您的NSDocument
子类以外的东西。
谢谢!今天会尝试!这种方法是自动调用还是必须在右击时调用它?谢谢 – sharkyenergy 2013-03-07 06:54:42
很长时间以来,我写它,但它应该只是自动发生,由于菜单插座连接 – 2013-03-07 07:27:42
谢谢!现在尝试,但我无法理解这一点:'//让你的数据对象提供菜单 NSMenu * newmenu = [thing menuThatMyThingProvides]; ' – sharkyenergy 2013-03-07 18:07:59