Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OSX Statusbar App using Swift [duplicate]

I am trying to write a status bar app for OSX using swift. The equivalent code in Objective-C seems to work and shows up a status bar menu, but the following code does not:

import Cocoa

class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet var statusMenu: NSMenu

    func applicationDidFinishLaunching(aNotification: NSNotification?) {
        // Insert code here to initialize your application
    }

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

    override func awakeFromNib() {
        var statusBar = NSStatusBar.systemStatusBar()
        var statusBarItem = statusBar.statusItemWithLength(CGFloat(NSVariableStatusItemLength))
        statusBarItem.menu = statusMenu
        statusBarItem.title = "TestApp"
    }

}
like image 526
Sharoon Thomas Avatar asked Jun 10 '14 08:06

Sharoon Thomas


1 Answers

Your statusBarItem var is going out of scope once the call to awakeFromNib() completes, you need to keep a reference to it. Try something like this:

import Cocoa

class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet var statusMenu: NSMenu
    var statusBarItem : NSStatusItem?


    override func awakeFromNib() {
        var statusBar = NSStatusBar.systemStatusBar()
        statusBarItem = statusBar.statusItemWithLength(CGFloat(NSVariableStatusItemLength))
        statusBarItem!.menu = statusMenu
        statusBarItem!.title = "TestApp"
    }

}
like image 82
MattR Avatar answered Oct 27 '22 00:10

MattR