這是一個代表! - 不需要子類
在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