Ad

StatusItem In MacOS Menubar Is Greyed Out And Doesn't Work

- 1 answer

I have some Swift code that looks like this. However the menu item will just be greyed out and not work. I have tried different versions for the #selector on the item, but so far nothing works.

class StatusBarController {
    private var statusBar: NSStatusBar
    private var statusItem: NSStatusItem
    
    init() {
        statusBar = NSStatusBar.init()
        self.statusItem = statusBar.statusItem(withLength: NSStatusItem.variableLength)
        

        self.state = FirebaseData()
        self.startUpdate()
        
        self.setupMenus()
        
    }
    
    func setupMenus() {
        let menu = NSMenu()

        menu.addItem(withTitle: "Play Pause", action: #selector(StatusBarController.onClickPlayPause), keyEquivalent: "1")

        menu.addItem(NSMenuItem.separator())

        menu.addItem(NSMenuItem(title: "Quit", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))

        self.statusItem.menu = menu
    }
    
    @objc func onClickPlayPause(sender : NSMenuItem) {
        if self.isRunning() {
            self.pause()
        } else if (self.state.intervalLeft != nil) {
            self.resume()
        } else {
            self.startTimer(nil)
        }
    }
}

Can someone explain to me what I'm doing wrong here? Thank you!

Play pause greyed out

Ad

Answer

You have to set the target.

let playMenuItem = menu.addItem(withTitle: "Play Pause", action: #selector(onClickPlayPause), keyEquivalent: "1")
playMenuItem.target = self

The Quit item works via First Responder.

Ad
source: stackoverflow.com
Ad