glenstorey glenstorey - 1 year ago 160
Swift Question

keyEquivalent with non-alpha numeric character in Swift

In a context menu, I'd like

to be a key equivalent.

In this support document, you can set it like so:

unichar arrowKey = NSLeftArrowFunctionKey;
[button setKeyEquivalent:[NSString stringWithCharacters:&arrowKey length:1]];

However, I'm struggling to convert this to Swift.

How can you set permitted non-alpha numeric keys as the key equivalent in Swift?

Answer Source

That code takes NSLeftArrowFunctionKey (a C macro), assigns it to a unichar variable, and then takes the address of it to give to NSString. Annoyingly, because it's a C macro and not a const, you can just directly use &NSLeftArrowFunctionKey.

In Swift, NSLeftArrowFunctionKey is imported as UInt16, which can be used to create a UnicodeScalar, which can be used to create a Character, and ultimately a String.

Use this in Swift 2:

button.keyEquivalent = String(Character(UnicodeScalar(NSLeftArrowFunctionKey)))

Use this in Swift 3:

button.keyEquivalent = String(Character(UnicodeScalar(NSLeftArrowFunctionKey)!))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download