需求:
在NSTableView里右键点击一下item刚焦点需要转移到此条目上,但默认行为不是这样的,而且在delegate里也无法实现,只能通过重写方法来实现,而且还需要调用已经废弃的方法。不过这个方法仍然有效。
子类实现:
- -(NSMenu*)menuForEvent:(NSEvent*)event
- {
- //Find which row is under the cursor
- [[self window] makeFirstResponder:self];
- NSPoint menuPoint = [self convertPoint:[event locationInWindow] fromView:nil];
- int row = [self rowAtPoint:menuPoint];
- /* Update the table selection before showing menu
- Preserves the selection if the row under the mouse is selected (to allow for
- multiple items to be selected), otherwise selects the row under the mouse */
- // BOOL currentRowIsSelected = [[self selectedRowIndexes] containsIndex:row];
- // if no row selected , the variable "row" will be -1
- if (row >= 0)
- {
- [self selectRow:row byExtendingSelection:NO];
- }
- // if no file selected , set the folder menu to the nstableview
- if (row < 0 )
- {
- return self.folderMenu;
- }
- else
- return self.tableItemMenu;
- }
这样点击空白处和点击条目会显示不同的菜单
而且焦点也处理的得当。
可以使用selectedRow来获取当前条目的index.
转载于:https://blog.51cto.com/bhlzlx/967631