Search code examples
objective-ccocoakeyboard-shortcutsnsbutton

Click a NSPushButton programmatically with "animation"


I just ran into a problem I already know from other programming languages/frameworks .... Whenever the user clicks a certain button on the keyboard, he triggers the same action than when a certain button in the GUI is pressed. ( Some guys call these "shortcuts" ;D )

To give the user an optical feedback, I would like to sorta "click" the button programmatically rather than calling the same functions that get called when the button is clicked.

If I set the button as a key equivalent in IB, it looks exactly as I want to have it. Can't do that here as the shortcut should just be enabled if the right textfields have focus.

Couldn't find a method in NSButton or similar that sounded right. I'm sure you guys can give me some direction!

Best and thanks in advance


Solution

  • You can just send performClick: to the button. It will highlight itself, send its action to its target, and then unhighlight itself.

    [self.someButton performClick:self];
    

    If you really want to just highlight and unhighlight the button manually, you can use the highlight: method.

    [self.someButton highlight:YES]; // button appears pressed
    [self.someButton highlight:NO]; // button appears unpressed