NSTableView
中右键单击的行索引,但我无法找到任何委托方法或类属性。欢迎提供任何建议。NSTableView
中右键单击的行索引,但我无法找到任何委托方法或类属性。欢迎提供任何建议。使用 NSTableView 方法 - (NSInteger)clickedRow
获取最后一次点击的行索引。返回的 NSInteger 将是右键单击行的索引。
您不需要为此解决方案子类化 NSTableView
。 clickedRow
在 NSOutlineView
上也可用。
虽然我没有做过这个,但我很确定你可以通过覆盖NSView
的- (NSMenu*)menuForEvent:(NSEvent*)theEvent
来实现。这个链接中的示例进行了点转换以确定索引。
-(NSMenu*)menuForEvent:(NSEvent*)theEvent
{
NSPoint mousePoint = [self convertPoint:[theEvent locationInWindow] fromView:nil];
int row = [self rowAtPoint:mousePoint];
// Produce the menu here or perform an action like selection of the row.
}
如果您想在菜单打开时获取点击行的索引,则答案是NSTableView.clickedRow
。无论如何,此属性仅在特定时刻可用,通常为-1
。
这个索引何时可用?即在NSMenuDelegate.menuWillOpen
方法中。因此,您需要符合代理并在您的类上实现该方法,并访问clickedRow
属性。完成了。
final class FileNavigatorViewController: NSViewController, NSMenuDelegate {
let ov = NSOutlineView() // Assumed you setup this properly.
let ctxm = NSMenu()
override func viewDidLoad() {
super.viewDidLoad()
ov.menu = ctxm
ctxm.delegate = self
}
func menuWillOpen(_ menu: NSMenu) {
print(outlineView.clickedRow)
}
}
在您单击菜单项之前,所单击的行索引是可用的。 因此,这也适用于此情况。
final class FileNavigatorViewController: NSViewController {
let ov = NSOutlineView() // Assumed you setup this properly.
let ctxm = NSMenu()
let item1 = NSMenuItem()
override func viewDidLoad() {
super.viewDidLoad()
ov.menu = ctxm
ov.addItem(item1)
ov.target = self
ov.action = #selector(onClickItem1(_:))
}
@objc
func onClickItem1(_: NSObject?) {
print(outlineView.clickedRow)
}
}
我在 macOS Sierra (10.12.5) 上进行了测试。
从 OS X 10.11 开始,Apple 终于添加了一种简单访问 clickedRow
的方法。只需子类化 NSTableView
并覆盖此方法,您将得到 clickedRow
(就我所知)。
func willOpenMenu(menu: NSMenu, withEvent event: NSEvent)
这需要子类化处理,但无论如何,访问clickedRow
的最干净和最简单的方法是。
此外,还有一种配对方法。
func didCloseMenu(menu: NSMenu, withEvent event: NSEvent?)
通过在NSTableView
子类中实现menuForEvent:
,可以在右键单击时选择行:
@implementation MyTableView
- (NSMenu *)menuForEvent:(NSEvent *)theEvent
{
int row = [self rowAtPoint:[self convertPoint:theEvent.locationInWindow fromView:nil]];
if (row == -1)
return nil;
if (row != self.selectedRow)
[self selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];
return self.menu;
}
@end
如果您不需要打开NSMenu,但需要知道“右键单击行号”的操作,我认为最简单的方法如下。(Swift4代码)不需要任何其他连接的外部NSMenu类。
class SomeViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
@IBOutlet weak var tableView: NSTableView!
...
override func viewDidLoad() {
...
tableView.action = #selector(some method()) // left single click action
tableView.doubleAction = #selector(someMethod()) // left double click action
}
// right click action
override func rightMouseDown(with theEvent: NSEvent) {
let point = tableView.convert(theEvent.locationInWindow, from: nil)
let row = tableView.row(at: point)
print("right click")
print(row)
}