Search code examples
macoscocoaswiftnsbutton

How to set NSButton's keyEquivalent to NSDownArrowFunctionKey in Swift


How do I set an NSButton's keyEquivalent (which is a String type) to the down arrow key in Swift? NSDownArrowFunctionKey is an Int.


Solution

  • This page in Apple's documentation addresses this exact issue. The example they provide is written in Objective-C, the Swift equivalent is as follows:

    import Cocoa
    
    @NSApplicationMain
    class AppDelegate: NSObject, NSApplicationDelegate {
    
        @IBOutlet weak var window: NSWindow!
        @IBOutlet weak var button: NSButton!
    
        func applicationDidFinishLaunching(aNotification: NSNotification) {
    
            var array = [unichar(NSDownArrowFunctionKey)]
            button.keyEquivalent = NSString(characters: array, length: 1)
        }
    }