NSApplication responder chain for arrow keys

℡╲_俬逩灬. 提交于 2020-05-24 05:33:08

问题


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.

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:



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)

First: K key event call stack; Second: Right arrow key event call stack

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

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


回答1:


Interesting observation about the call stack difference. Since arrow keys play the most important role in navigation they are probably handled differently from the rest of keys, like you saw in the NSMenuItem KeyEquivalent space " " bug thread. Again, it's one of those cases when AppKit takes care of everything behind the scenes to make your life easier in 99.9% situations.

You can see the actual difference in behaviour by pressing k while textfield has the focus. Unlike with arrows, the menu item's key equivalent doesn't get triggered and input goes directly into the control.

For your situation you can use NSMenuItemValidation protocol to override the default action of enabling or disabling a specific menu item. AFAIK this can go into any responder in a chain, e.g., view controller, window, or application. So, you can enable/disable your menu items in a single place when the window's first responder is a textfield or any other control that uses these events to properly operate.

extension ViewController: NSMenuItemValidation {
    func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
        // Filter menu item by it's assigned action, just as an exampe.
        if menuItem.action != #selector(ViewController.menuActionLeftArrowKey(_:)) { return true }
        Swift.print("Validating menu item:", menuItem)
        // Disable the menu item if first responder is text view.
        let isTextView = self.view.window?.firstResponder is NSTextView
        return !isTextView
    }
}

This will get invoked prior displaying the menu in order to update item state, prior invoking menu item key equivalent in order to check if action needs sending or not, and probably in other cases when AppKit needs to check the item's state – can't think of any from the top of my head.

P.S. Above the first responder check is done against NSTextView not NSTextField, here's why.




回答2:


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

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.

These are the key codes

  • 123: right arrow
  • 124: left arrow
  • 125: down arrow
  • 126: up arrow


来源:https://stackoverflow.com/questions/61839795/nsapplication-responder-chain-for-arrow-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!