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"
}
}
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"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With