使用 'j' 模拟箭头键和“k”在 NSTableView 中?
我有一个包含多行的 NSTableView。 allowedEmptySelection 属性为 NO,因此始终会选择一行。我可以按预期使用箭头键在表格视图中上下移动。
我还希望能够使用“j”和“k”键上下移动。我查看了 Cocoa 事件处理指南,但无法弄清楚如何使这些键模拟向上和向下箭头键。
就其价值而言,这就是我目前正在做的事情。我并不是真的在“模拟箭头键”。相反,我只是在按下“j”和“k”时执行我想要的行为。很好,但是我想知道是否有更好的方法...
- (void)keyDown:(NSEvent *)theEvent {
NSInteger row = [self.tableView selectedRow];
NSInteger numRows = [self.tableView numberOfRows];
switch ([theEvent keyCode]) {
case 38: // 'j'
if (row < numRows - 1) {
[self.tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:row+1] byExtendingSelection:NO];
}
break;
case 40: // 'k'
if (row > 0) {
[self.tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:row-1] byExtendingSelection:NO];
}
break;
default:
[super keyDown:theEvent];
}
}
I have an NSTableView with a number of rows. The allowsEmptySelection property is NO, so there is always a row selected. I can move up and down the tableview with the arrow keys as expected.
I'd like to also be able to move up and down with the 'j' and 'k' keys. I've looked at the Cocoa Event-Handling Guide, but can't figure out how to make these keys simulate the up and down arrow keys.
For what it's worth, here's what I'm currently doing. I'm not really 'simulating the arrow keys'. Rather, I'm just doing the behavior I want when 'j' and 'k' are pressed. It's fine, but I'm wondering if there is a better way...
- (void)keyDown:(NSEvent *)theEvent {
NSInteger row = [self.tableView selectedRow];
NSInteger numRows = [self.tableView numberOfRows];
switch ([theEvent keyCode]) {
case 38: // 'j'
if (row < numRows - 1) {
[self.tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:row+1] byExtendingSelection:NO];
}
break;
case 40: // 'k'
if (row > 0) {
[self.tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:row-1] byExtendingSelection:NO];
}
break;
default:
[super keyDown:theEvent];
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
创建 NSTableView 的自定义子类来捕获事件。您的子类中应该包含此方法:
这将捕获任何 J 或 K 键并分别告诉表视图向上或向下移动。另外,如果按下 Shift 键,则会向上或向下添加选择。
如果您选择使用此代码,请确保过滤掉是否按下了任何其他修饰符并将它们也传递给 super。我这样做并不是为了让它更具可读性。
编辑:如何创建虚假事件
Create a custom subclass of NSTableView to catch the events. Your subclass should have this method in it:
This will catch any J or K keys and tell the table view to move up or down, respectively. Also, if the shift key is pressed, this will add to the selection upwards or downwards.
If you choose to use this code, make sure you filter out if any other modifiers are pressed and pass them to super also. I did not do this to make it more readable.
Edit: How to create a false event