NSTableView右鍵菜單解決方案

 需求:ide

在NSTableView裏右鍵點擊一下item剛焦點須要轉移到此條目上,但默認行爲不是這樣的,並且在delegate裏也沒法實現,只能經過重寫方法來實現,並且還須要調用已經廢棄的方法。不過這個方法仍然有效。spa

子類實現:ip

 

  
  
  
  
  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; 

這樣點擊空白處和點擊條目會顯示不一樣的菜單it

並且焦點也處理的得當。io

可使用selectedRow來獲取當前條目的index.event

相關文章
相關標籤/搜索