0

I have a menu with menu items. The problem is that my menu items are all greyed out or not enabled

public override init() {
  super.init()

  let menu = NSMenuItem(title: "Debug", action: nil, keyEquivalent: "")
  menu.submenu = NSMenu(title: "Debug")
  menu.submenu?.addItem(withTitle: "Load saved data", action: #selector(loadDataFromFile(_:)), keyEquivalent: "");
  menu.submenu?.addItem(withTitle: "another item", action: #selector(loadDataFromFile(_:)), keyEquivalent: "")
  menu.isEnabled = true
  
  NSApplication.shared.mainMenu?.addItem(menu)

}

 @objc func loadDataFromFile(_ sender: Any) {
      print("load it")
  }

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • 2
    Does this answer your question? [menu item is enabled, but still grayed out](https://stackoverflow.com/questions/4870141/menu-item-is-enabled-but-still-grayed-out) – Willeke Jun 07 '22 at 09:43
  • If I'm not mistaken, a `nil` `target` of an `NSMenuItem` indicates that the target should be the responder chain. The item being greyed out is because nothing in your responder chain responds to the selectors you've specified. Either add the necessary objects to the responder chain, or set some other object as the target to receive these messages – Alexander Jun 07 '22 at 13:17

1 Answers1

1

To be able to call a custom selector in the current class you have to set the target of the menu item to self

let menu = NSMenuItem(title: "Debug", action: nil, keyEquivalent: "")
menu.submenu = NSMenu(title: "Debug")
let loadItem = NSMenuItem(title: "Load saved data", action: #selector(loadDataFromFile), keyEquivalent: "")
loadItem.target = self
let anotherItem = NSMenuItem(title: "another item", action: #selector(loadDataFromFile), keyEquivalent: "")
anotherItem.target = self
menu.submenu?.addItem(loadItem)
menu.submenu?.addItem(anotherItem)
menu.isEnabled = true
vadian
  • 274,689
  • 30
  • 353
  • 361