Question

I want to be able to handle three different key combinations when a user is editing a NSTextField:

  • ⌘↩
  • ⇧↩

Each of these combinations will be responded to differently.

Ideally, I would like to achieve this through IB alone. However, my understanding is that Cocoa only allows one sent action per control.

I can bind this sent action to an IBAction and set the NSTextField to only send it when the return key is pressed, but I can't find a way to get which modifier keys are currently held down (as the action only receives (id)sender, not an event object). Is that possible?

Alternatively, I guess it would be possible to subclass NSTextField, override keyDown:, and manually run the appropriate actions. However, I can't think of how to wire this up correctly in IB. (I could use an IBOutlet for the target, but I can't think of a way to wire up a specific method.) I'm also worried about the efficiency of this approach.

What is the normal way of handling certain key events on an NSTextField?


The approach which I'm leaning towards at the moment is writing a custom protocol and putting an outlet on the text field subclass:

@property (weak, nonatomic) IBOutlet id<TextFieldReturnHandler> target

which could then be called from the keypress event. This seems really convoluted, though.

Was it helpful?

Solution

You can wire the sent action up to a method on your controller:

- (IBAction)cellDidEndEditing:(id)sender;

If you only want this method to be called when the return key is pressed, and not, eg, when the user clicks away, you can set the Action property on the NSTextField in IB to 'Send On Enter Only' instead of 'Send On End Editing'.

Within this method, you can access the event with:

NSEvent *evt = [NSApp currentEvent];

After checking whether the event is valid, you can obtain and act on the necessary modifier flags:

if (evt && evt.type == NSKeyDown) {
    evt.modifierFlags // NSShiftKeyMask, NSCommandKeyMas, NSAlternateKeyMask

    // Perform actions
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top