Search code examples
swiftmacoscocoansviewcontroller

How to attach a custom menu to the main view in a OS X desktop app in Swift


Given the following GitHub project:

https://github.com/kellyjanderson/swift-custom-menue

How do I link the menu item Custom >> Custom Action, to the function customAction in the ViewController?


Solution

  • Define an outlet of your menu item in AppDelegate

    @IBOutlet weak var customMenuItem: NSMenuItem!
    

    In your view controller first get the instance of AppDelegate:

     let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
    

    Get the instance of the menu item and then bind an IBAction to it:

    appDelegate.customMenuItem.action = #selector(customAction(_:))
    

    For e.g., you want to bind an action customAction to your menu item. You can add the following code in viewDidLoad

     override func viewDidLoad() {
            super.viewDidLoad()
             let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
             print(appDelegate.customMenuItem)
            appDelegate.customMenuItem.action = #selector(customAction(_:))
        }
    

    And then define the IBAction

     func customAction(sender: NSMenuItem){
            print("Custom Menu Item clicked")
        }
    

    Output:

    <NSMenuItem: 0x6080000a0720 Custom Action>
    Custom Menu Item clicked