Search code examples
swiftuimenuitem

How to enable own menu item in SwiftUI app


I have SwiftUI app with storyboard menu where I added my own item which is disabled when I run the app. I created following class to make it enabled and I call initMenu method from applicationDidFinishLaunching in AppDelegate but menu item still remains disabled, what else or additional I have to do to make it enabled?

class MenuActions: NSObject {

func initMenu() {
    let mainMenu = NSApplication.shared.mainMenu
    mainMenu?.autoenablesItems = false
    mainMenu?.item(at: 1)?.submenu?.item(at: 0)?.isEnabled = true
}

@IBAction func new(_ sender: NSMenuItem) {
    print("fired")
}

}

Solution

  • Inside AppDelegate you can just add the IBaction

    @IBAction func new(_ sender: NSMenuItem) {
        print("fired")
    }
    

    Then connect the Menu Item in the Storyboard file with that function and it is enabled by default.

    Edit:

    You can create your own Menu class which handles the MenuItems action like this:

    class MenuItems : NSObject {
        @IBAction func new(_ sender: NSMenuItem) {
            print("fired")
        }
    }
    

    Then add an Object in the storyboard to the Application Scene and set your custom class to that object. Thereafter connect your IBactions

    enter image description here

    enter image description here