Search code examples
swiftmacosnsmenunsmenuitem

Where can I declare my trigger for NSMenu?


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


Solution

  • 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.