Cocoa: setting the key equivalent

Eike Cochu picture Eike Cochu · Jun 3, 2011 · Viewed 9.8k times · Source

i want to set the key equivalent of a menuitem with [menuitem setKeyEquivalent:(NSString *)s], how can i do that if i have multiple modifiers ?

i tried:

unichar shift = NSShiftKeyMask, cmd = NSCommandKeyMask;
NSMutableString *keyequiv = [[NSMutableString alloc] init];

[keyequiv appendString:[NSString stringWithCharacter:&shift, 1]];
[keyequiv appendString:[NSString stringWithCharacter:&cmd, 1]];
[keyequiv appendString:@"x"];
[menuItem setKeyEquivalent:keyequivalent];

but that doesnt work.

Answer

jscs picture jscs · Jun 3, 2011

The modifier key masks are just that: masks, not characters. You can't insert them into the key equivalent string. To apply them, use setKeyEquivalentModifierMask:

[menuItem setKeyEquivalentModifierMask: NSShiftKeyMask | NSCommandKeyMask];
[menuItem setKeyEquivalent:@"x"];

As with any other mask, use the bitwise OR operator | to form combinations. See "Setting a Menu Item's Key Equivalent" for more details.