I am trying to create an application that will display a menu bar extra on macOS.
I used a lot of code I've found on the web so far, but, while all of them compile, none actually display the menu.
The code snippets are more or less like this:
@NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var statusBarItem: NSStatusItem! func applicationDidFinishLaunching(_ aNotification: Notification) { let statusBar = NSStatusBar.system statusBarItem = statusBar.statusItem( withLength: NSStatusItem.squareLength) statusBarItem.button?.title = "🌯" let statusBarMenu = NSMenu(title: "Cap Status Bar Menu") statusBarItem.menu = statusBarMenu statusBarMenu.addItem( withTitle: "Order a burrito", action: #selector(AppDelegate.orderABurrito), keyEquivalent: "") statusBarMenu.addItem( withTitle: "Cancel burrito order", action: #selector(AppDelegate.cancelBurritoOrder), keyEquivalent: "") } @objc func orderABurrito() { print("Ordering a burrito!") } @objc func cancelBurritoOrder() { print("Canceling your order :(") } Nothing is displayed on the menu. Is there anything I need to enable to make it display the menu? I tried with images as well, it didn't work either.
statusItemWithLength:says: "The receiver does not retain a reference to the status item, so you need to retain it. Otherwise, the object is removed from the status bar when it is deallocated." Perhaps you should try keeping a strong reference to yourstatusBarItem?var statusBarItem: NSStatusItem!, but maybe it needs to be outside the class?statusBarItemvariable drops out of scope at the end of theapplicationDidFinishLaunchingand will therefore be released. You need to keep a reference at the class level (a class member or property).