Bryan James
Bryan James

Reputation: 23

Actions assigned to NSMenuItem dont seem to work

Heres whats going on:

I am attempting to build a Mac Status Bar App completely programmatically. Everything seems to be working fine, that is the menu shows up in the Mac status bar, the dropdown menu is displaying how it should. But when I click on the menu items, nothing happens. I even changed the target function to just doing the basic task of printing to the terminal, and nothing.


About the code:

The issue lies somewhere around here I think:

menu.addItem(NSMenuItem(title: val, action: #selector(toggleService), keyEquivalent: ""))

That code should fire off the > toggleService function. But it doesn't do anything. Could the issue be due to the fact that I am only inheriting from the NSObject class?


The Code

// StatusBar.swift

import Cocoa

class StatusBar: NSObject {

    var menuButton = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
    var menu = NSMenu()
    var service = Service()

    override init() {
        super.init()
        menuButton.button?.image = NSImage(named: NSImage.Name("icon"))
        menuButton.menu = menu
        menu.autoenablesItems = false
        for (_, val) in service.list {
            menu.addItem(NSMenuItem(title: val, action: #selector(toggleService), keyEquivalent: ""))
        }
        menu.addItem(NSMenuItem.separator())
        menu.addItem(NSMenuItem(title: "Quit", action: #selector(quit), keyEquivalent: ""))
    }

    @objc func toggleService(sender: NSMenuItem) {
        print ("Say Something.. anything??")
    }

    @objc func quit(sender: NSMenuItem) {
        print ("Say Something.. anything??")
    }

}

Upvotes: 2

Views: 702

Answers (1)

Brennan Walsh
Brennan Walsh

Reputation: 460

menuItem.target = self

You need to set the target to 'self'. NSMenuItems have two basic requirements. An action, and a target,

  1. Action menuItem.action: #selector(YOURFUNCTION)

  2. Target menuItem.target = self

So to get your menu items working, replace the for loop (within your init call) with this new one:

for (_, val) in service.list {
    let menuItem = menu.addItem(NSMenuItem(title: val, action: #selector(toggleService), keyEquivalent: ""))
    menuItem.target = self
}

Upvotes: 5

Related Questions