Question

I have a window with two NSButtons and an NSTextField along with several views and several other controls. I assign the right and left arrows keys to each of the two NSButtons. The two buttons respond to the right and left arrow keys. However, when in the NSTextField, I want the arrow keys to perform as the normally would in a text field and not trigger the NSButtons. I have tried reading through the Cocoa Key Handling documentation and other questions regarding key events, but I could not find an example of trying change the key equivalent behavior in one control. I tried subclassing the NSTextField but couldn't trap the arrow keys. How can this be implemented?

Was it helpful?

Solution

You can override becomeFirstResponder: and in your implementation call setKeyEquivalent:. If you want to remove the key equivalent when the button loses first responder status, override resignFirstResponder:.

Do this in the control whose first-responder status you want to affect the button's equivalent. For example, if you have a view as a container and it can become first responder, you'd override -becomeFirstResponder: (calling super) then manage the button's equivalent there. If you don't yet understand these topics, you have a lot of prerequisite reading to do because a simple answer isn't possible here.

OTHER TIPS

You could subclass NSButton and override performKeyEquivalent: like so:

override func performKeyEquivalent(event: NSEvent) -> Bool {
    guard
        let window = window where window.firstResponder.isKindOfClass(NSText.self) == false
    else {
        return false
    }

    return super.performKeyEquivalent(event)
}

This essentially disables the key equivalent if the first responder is a text field/view.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top