Search code examples
swiftmacosnsstatusitemnsstatusbar

How to update a NSStausItem from another file?


I want to update the button.title property of a NSStausItem in the status bar, when the user klicks a button in my settings view. However, the NSStatusItem currently does not change.

AppDelegate:

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

func applicationDidFinishLaunching(_ aNotification: Notification) {
    statusItem.button?.title = "A title"
}

func updateTitle(newTitle : String) {
    statusItem.button?.title = newTitle
}

SettingsViewController:

@IBAction func didKlickChange(_ sender: Any) {
    AppDelegate().updateTitle(newTitle: "Updated title")
}

When I run the app the StatusBar show a new StatusItem with the title "A title". So good, so far. But when I klick on the button, the only thing that happens is that a new status item appears for a very short time next to the old status item. The old one does not get updated. Is there a proper solution for that?

Thanks for your help!


Solution

  • AppDelegate() creates a brand new instance of the class which is not the instance you expect. You need the actual reference

    @IBAction func didKlickChange(_ sender: Any) {
        (NSApp.delegate as! AppDelegate).updateTitle(newTitle: "Updated title")
    }