Search code examples
macosswiftstatusbar

Swift: Refresh menu bar on click


I am making a status bar application for Mac OS X however I only want it to refresh when I click the status bar item.

Here is my code:

class AppDelegate: NSObject, NSApplicationDelegate {
    @IBOutlet weak var window: NSWindow!
    @IBOutlet var menu: NSMenu!


    var statusItem: NSStatusItem!;

    @IBAction func quit(sender: AnyObject) {
        NSApplication.sharedApplication().terminate(nil)
    }

    func Refresh(){
        NSLog("Refresh")
    }

    func applicationDidFinishLaunching(aNotification: NSNotification?) {
        statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1)
        statusItem.title = "Battery Infomation"
        statusItem.menu = self.menu
        statusItem.highlightMode = true
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }


}

If any one can help me to do this that would be appreciated.


Solution

  • What you are looking for is validateMenuItem:. It's a place to check if the menu should be enabled or disabled. So, it get called just before the menu show up every time. You can use it to update title to reflect the battery status.

    override func validateMenuItem(menuItem: NSMenuItem) -> Bool {
        if(menuItem.action == Selector("batteryStatus:")) {
            NSLog("refresh!");
            let now = NSDate()
            menuItem.title = String(format:"%f", now.timeIntervalSince1970);
            return true;
        }
        return true;
    }
    
    @IBAction func batteryStatus(sender: NSObject) {
    
    }