user3126921
user3126921

Reputation: 23

OS X Application Keyboard Shortcuts

I am making my first OS X application in Xcode, and I have no idea how to make a specified keyboard shortcut trigger some code (e.g. ⌘ Cmd+ C/⌘ Cmd+V). All I can find online is keyboard shortcuts in Xcode itself.

Thanks in advance

Upvotes: 0

Views: 576

Answers (1)

Per Johansson
Per Johansson

Reputation: 6887

This is usually setup for you automatically. The MainMenu.xib by default has an Edit menu with these shortcuts bound, activating [firstResponder copy:] and [firstResponder paste:]. The first responder is item currently having keyboard focus, or it's parent view if it doesn't answer to those actions, up to the window at the top level.

For new shortcuts, Apple recommends that you have menu items associated to all those. If you do, you can set the shortcut in the interface builder using the attributes inspector. You then ctrl-drag from the menu item to the object you want to send the action to, e.g. the app delegate. You will have to create the target method first obviously. You should also use bindings to control when the menu item is enabled or not.

It's not recommended, but if you want to do this programmatically, without a menu item, you override the

- (BOOL)performKeyEquivalent:(NSEvent *)theEvent

method of the view or window in question. It will be called if it's in the responder chain when the key is pressed, and you return YES to indicate you've handled the event.

Upvotes: 1

Related Questions