Set menubar icon from ViewController

1k Views Asked by At

How to change the menubar icon of a MacOS app from another ViewController?

  • AppDelegate.swift (inits menubar icon)
  • ViewController.swift (tries to set menubar icon ❌)

I found this but this isn't changing the menubar icon for me: Mac: How to save alternate app icon in dock OSX xcode

let image = NSImage.init(named: NSImage.Name(rawValue: "AltAppIcon"))
NSApp.applicationIconImage = image

See how the BOINC icon has the little custom pause symbol/badge in the bottom right of it's menubar? This app's icon changes. Are they writing over the name of that file and changing it to the "paused icon" image maybe?

BOINC menubar icon paused


UPDATE*

A AppDelegate.swift function that set the menubar icon worked:

AppDelegate.swift

func setIcon() {
  let onIcon = NSImage(named: "fv-mini-icon-green")
  statusItem.button?.image = onIcon
}

ViewController.swift

func taskOnIcon() {
  DispatchQueue.main.async(execute: {
    let appDele = NSApplication.shared.delegate as! AppDelegate
    appDele.setIcon()
  })
}
1

There are 1 best solutions below

0
Asperi On BEST ANSWER

Here is a way...

class AppDelegate: NSObject, NSApplicationDelegate {
    var statusBarItem: NSStatusItem!

    func applicationDidFinishLaunching(_ aNotification: Notification) {

        let statusBar = NSStatusBar.system
        statusBarItem = statusBar.statusItem(withLength: 16)

        let button = statusBarItem.button
        button?.image = NSImage(named: "fv-mini-icon-green")

    // .. other code here