swiftcocoansmenunsstatusbar

MacOS statusbar app show menu and run function on click with swift 3


I'm making a small menubar app with Swift 3, I want the app to reload some data when I click the icon, but I also want it to show the statusMenu?

Below is a sample of my code:

//  AppDelegate.swift

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var statusMenu: NSMenu!

    @IBAction func quitClicked(_ sender: NSMenuItem) {
        NSApplication.shared().terminate(self)
    }

    let statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        if let button = statusItem.button {
            button.title = "App"
            button.action = #selector(AppDelegate.doSomething(sender:))
            statusItem.menu = statusMenu
        }
    }

    func applicationWillTerminate(_ aNotification: Notification) {
    }

    func doSomething(sender: AnyObject?) {
        NSLog("do something")
    }


}

if I comment out

// statusItem.menu = statusMenu 

The doSomething() function will run, but I can't figure out how to both show the menu and run the doSomething function, how can I do that?


Solution

  • Set the delegate of the menu to the application delegate (or another object) and implement optional func menuWillOpen(_ menu: NSMenu) of the NSMenuDelegate protocol.