Cocoa: setting the key equivalent
Asked Answered
W

5

21

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.

Wrong answered 3/6, 2011 at 16:21 Comment(1)
Any way to setup F1 as the key equivalent? thxSaphead
B
31

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.

Behling answered 3/6, 2011 at 18:1 Comment(1)
Note that NSShiftKeyMask, NSCommandKeyMask etc are deprecated. Instead use NSEventModifierFlagShift, NSEventModifierFlagCommand , etc.Diamante
O
15

The setKeyEquivalent: method is used to specify the character which triggers the command, but not the modifiers. It will set default modifiers by examining the character you pass. If you pass a lowercase character, it will use just command. If you pass an uppercase character, it will use shift+command. Because of this, you simply need to do this for shift+command+x:

[menuItem setKeyEquivalent:@"X"];

If you want to use other modifiers, you then call setKeyEquivalentModifierMask: with the proper constants, chosen from NSShiftKeyMask, NSAlternateKeyMask (option), NSCommandKeyMask, and NSControlKeyMask.

Orphanage answered 3/6, 2011 at 18:0 Comment(0)
V
3

Example for Swift 2.0:

let key = String(utf16CodeUnits: [unichar(NSBackspaceCharacter)], count: 1) as String
item.keyEquivalentModifierMask = Int(NSEventModifierFlags.CommandKeyMask.rawValue | NSEventModifierFlags.ControlKeyMask.rawValue)
item.keyEquivalent = key
Vickery answered 30/7, 2015 at 17:4 Comment(0)
J
2

Example for Swift 3.0:

item.keyEquivalent = "x"
item.keyEquivalentModifierMask = [NSAlternateKeyMask, NSCommandKeyMask]
Jessicajessie answered 8/3, 2017 at 17:15 Comment(0)
P
2

Example for Swift 5:

item.keyEquivalent = "q"
item.keyEquivalentModifierMask = [.command]
Pusey answered 3/6, 2020 at 9:47 Comment(1)
item.keyEquivalentModifierMask = .option.union(.command)Beachhead

© 2022 - 2024 — McMap. All rights reserved.