8

From NSMenuItem Class Reference

If you want to specify the Backspace key as the key equivalent for a menu item, use a single character string with NSBackspaceCharacter (defined in NSText.h as 0x08) and for the Forward Delete key, use NSDeleteCharacter (defined in NSText.h as 0x7F).

Not sure I understand "use a single character string with..." from the class ref.

// This works as expected

NSString *s = [NSString stringWithFormat:@"%c",NSDeleteCharacter];

    [myMenuItem setKeyEquivalentModifierMask:NSCommandKeyMask];

    [myMenuItem setKeyEquivalent:s];

enter image description here

// This doesn't works as expected

NSString *s = [NSString stringWithFormat:@"%c",NSF2FunctionKey];

    [myMenuItem setKeyEquivalentModifierMask:NSCommandKeyMask];

    [myMenuItem setKeyEquivalent:s];

enter image description here

4

3 回答 3

5

我自己想通了。

   unichar c = NSF2FunctionKey;

    NSString *f2 = [NSString stringWithCharacters:&c length:1];

    [mi setKeyEquivalent:f2];
    [mi setKeyEquivalentModifierMask:NSCommandKeyMask];

在此处输入图像描述

于 2013-08-22T20:02:36.727 回答
4

斯威夫特 2.0 的例子:

let key = String(utf16CodeUnits: [unichar(NSBackspaceCharacter)], count: 1) as String
menuItem.keyEquivalentModifierMask = Int(NSEventModifierFlags.CommandKeyMask.rawValue)
menuItem.keyEquivalent = key
于 2015-07-30T16:58:22.897 回答
4

Swift 3、4 和 5 中:

let f2Character: Character = Character(UnicodeScalar(NSF2FunctionKey)!)
myMenuItem.keyEquivalent = String(f2Character)
myMenuItem.keyEquivalentModifierMask = []
于 2016-10-07T14:25:06.370 回答