Where can I declare my trigger for NSMenu?

200 Views Asked by At

I manually created an NSMenu in my AppDelegate like so:

class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {


  func applicationDidFinishLaunching(_ notification: Notification) {
        
    rightClickMenu = RightClickMenu.createMenu();

  }

And I want to keep all triggers for my NSMenu in a separate Class like that:

class RightClickMenu {
    static func createMenu() -> NSMenu {
        let menu = NSMenu(title: "Status Bar Menu")
         menu.addItem(
            withTitle: "Test",
            action: #selector(RightClickMenu.test(_:)),
            keyEquivalent: "")

        return menu

    }
    
    //This func never gets triggered and menu item is grey
    @objc func test(_ sender: Any?){
        print("Test")
    }
    
}

I think it has something to do with the location where the function is declared. At least I know that it works in the AppDelegate but why does it not work here? Couldn't find a good source to explain this Lifecycle at all...

I am coming from a SwiftUI Background only and I am a newbie in Swift and it is a little challenging to learn all this old tech it is based on. Hope you can help me.

This is how it looks like:

enter image description here

4

There are 4 best solutions below

0
Willey3x37 On BEST ANSWER

My answer to this was to use an Storyboard NSMenu from the SwiftUI default Project with an AppDelegate. This works perfect, so I recommend this as an solution for this.

0
flanker On

You are expressing the method in the selector as a static function (by referencing it on the class). Change it to

action: #selector(test(_:))

0
dengST30 On

you can try

let eventHud = RightClickMenu()

class RightClickMenu {

    static func createMenu() -> NSMenu {
        let menu = NSMenu(title: "Status Bar Menu")
        let item = NSMenuItem(title: "Test", action:  #selector(RightClickMenu.test(_:)), keyEquivalent: "")
        item.target = eventHud
        menu.addItem(item)
        return menu
    }
    
    
    @objc func test(_ sender: Any?){
        print("Test")
    }
    
}
0
black_pearl On

As RightClickMenu is just sth boilerplate,

better to modify it as

extension NSMenu{

    static func createMenu() -> NSMenu {
        let menu = NSMenu(title: "Status Bar Menu")
        let item = NSMenuItem(title: "Test", action:  #selector(NSMenu.test(_:)), keyEquivalent: "")
        item.target = menu
        menu.addItem(item)
        return menu
    }
    
   
    @objc func test(_ sender: Any?){
        print("Test")
    }
    
}