NSApplication响应程序链(用于箭头键) [英] NSApplication responder chain for arrow keys

查看:108
本文介绍了NSApplication响应程序链(用于箭头键)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的窗口中有一个NSTextField,并且有4个菜单项,其等效键为 .

I have an NSTextField in my window and 4 menu items with key equivalents .

当选定文本字段和余按箭头键,我希望光标在文本字段中移动,而是在执行对应的菜单项的动作.

When the text field is selected and I press an arrow key, I would expect the cursor to move in the text field but instead the corresponding menu item action is performed.

因此,响应者链中一定有一个问题.为了找出问题所在,我观看了 WWDC 2010会话145 –关键事件处理此 NSMenuItem KeyEquivalent space" bug 线程中提到的可可应用程序.

So there has to be an issue in the responder chain. To figure out what's wrong I've watched WWDC 2010 Session 145 – Key Event Handling in Cocoa Applications mentioned in this NSMenuItem KeyEquivalent space " " bug thread.


会话中显示了键(热键)的事件流,如下所示:


The event flow for keys (hotkeys) is shown in the session as follows:



因此,我使用具有keyEquivalent = K的菜单项(只是任何普通键)和具有keyEquivalent = →的菜单项(向右箭头键)检查了调用堆栈



So I checked the call stack with a menu item which has keyEquivalent = K (just any normal key) and for a menu item which has keyEquivalent = → (right arrow key)

首先:K键事件调用堆栈;第二:向右箭头键事件调用堆栈

因此,按箭头键时,事件直接发送到mainMenu.performKeyEquivalent,但是实际上应该发送到keyWindow,对吗?

So when pressing an arrow key, the event is sent directly to mainMenu.performKeyEquivalent, but it should actually be sent to the keyWindow right?

这是为什么?如何解决此问题,以便我的NSTextFieldmainMenu之前先收到箭头键事件?

Why is that and how can I fix this behavior so that my NSTextField receives the arrow key events before the mainMenu does?

推荐答案

这是我选择的解决方案,它来自@Willeke的评论.

This is the solution I've chosen, which resulted from the comments from @Willeke.

我创建了NSWindow的子类并覆盖了keyDown(with:)方法.我的应用程序中的每个窗口(当前为2个)都继承了这个新的NavigationWindow子类,以便您可以在每个窗口中使用箭头键.

I've created a subclass of NSWindow and overridden the keyDown(with:) method. Every Window in my application (currently 2) subclass this new NavigationWindow, so that you can use the arrow keys in every window.

class NavigationWindow: NSWindow {

    override func keyDown(with event: NSEvent) {
        if event.keyCode == 123 || event.keyCode == 126 || event.specialKey == NSEvent.SpecialKey.pageUp {
            print("navigate back")
        } else if event.keyCode == 124 || event.keyCode == 125 || event.specialKey == NSEvent.SpecialKey.pageDown {
            print("navigate forward")
        } else {
            super.keyDown(with: event)
        }
    }
}

此实现会注册所有四个箭头键以及用于导航的上翻页和下翻页键.

This implementation registers all four arrow keys plus the page up and down keys for navigation.

这些是关键代码

  • 123:向右箭头
  • 124:向左箭头
  • 125:向下箭头
  • 126:向上箭头
  • 123: right arrow
  • 124: left arrow
  • 125: down arrow
  • 126: up arrow

这篇关于NSApplication响应程序链(用于箭头键)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆