2

I'm trying to add an item to the status bar, but when I launch the app the item only appears in the top left for a split second and then quickly disappears.

I've looked through the documentation and I can see things have changed recently e.g. statusItem.title has become statusItem.button?.title. But don't seem to be missing anything else. Any help?

Here's my code:

var statusItem : NSStatusItem? = nil

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application

        let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
        statusItem.button?.title = "Connect!"

}
grooveplex
  • 2,492
  • 4
  • 28
  • 30
Jack Vanderpump
  • 216
  • 2
  • 16

2 Answers2

2

Ah brilliant. That's worked! Thanks Saleh. After playing around with both our codes, mine seemed to work with the var declaration at the top and without NSMenuDelegate instance. My issue seems to be that I was saying :

let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)

All I had to do to make it work was remove the 'let' and just say:

statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)

Jack Vanderpump
  • 216
  • 2
  • 16
  • So weird dude! Just by declaring the var outside of appDidFinishLaunching the whole thing worked. – arthas May 20 '21 at 19:46
1
  1. AppDelegate should be an instance of NSMenuDelegate
  2. Define the statusItem at creation
  3. Setup the button title in the applicationDidFinishLaunching callback

    class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
    let statusItem = NSStatusBar.system.statusItem(withLength:NSStatusItem.variableLength)
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        if let button = statusItem.button {
            //button.image = NSImage(named:NSImage.Name("StatusBarButtonImage"))
            button.title = "connect"
            //button.action = #selector(doSomething(_:))
        }
    }
    
Saleh Altahini
  • 373
  • 2
  • 12