需求:

在NSTableView里右键点击一下item刚焦点需要转移到此条目上,但默认行为不是这样的,而且在delegate里也无法实现,只能通过重写方法来实现,而且还需要调用已经废弃的方法。不过这个方法仍然有效。

子类实现:

 

 
  
  1. -(NSMenu*)menuForEvent:(NSEvent*)event 
  2.     //Find which row is under the cursor 
  3.     [[self window] makeFirstResponder:self]; 
  4.     NSPoint menuPoint = [self convertPoint:[event locationInWindow] fromView:nil]; 
  5.     int row = [self rowAtPoint:menuPoint]; 
  6.     /* Update the table selection before showing menu 
  7.      Preserves the selection if the row under the mouse is selected (to allow for 
  8.      multiple items to be selected), otherwise selects the row under the mouse */ 
  9. //  BOOL currentRowIsSelected = [[self selectedRowIndexes] containsIndex:row];     
  10.     // if no row selected , the variable "row" will be -1 
  11.     if (row >= 0) 
  12.     { 
  13.         [self selectRow:row byExtendingSelection:NO]; 
  14.     } 
  15.     // if no file selected , set the folder menu to the nstableview 
  16.     if (row < 0 ) 
  17.     { 
  18.         return self.folderMenu; 
  19.     } 
  20.     else 
  21.         return self.tableItemMenu; 

这样点击空白处和点击条目会显示不同的菜单

而且焦点也处理的得当。

可以使用selectedRow来获取当前条目的index.