The Wanderer
The Wanderer

Reputation: 23

Override key equivalent for NSButton in NSTextField

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?

Upvotes: 2

Views: 964

Answers (2)

Berk
Berk

Reputation: 367

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.

Upvotes: 0

Anoop Vaidya
Anoop Vaidya

Reputation: 46543

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.

Upvotes: 2

Related Questions