NSMenuItem is not enabled swift

2020-06-20 05:22发布

问题:

I have a NSMenuItem in my project:

var statusBar = NSStatusBar.systemStatusBar()
var statusItem : NSStatusItem = NSStatusItem()
var menuItem : NSMenuItem = NSMenuItem()
var mainMenu = NSMenu()

override func viewDidLoad() {
    super.viewDidLoad()

    menuItem.title = "Holidays"
    menuItem.action = Selector("setWindowVisible:")
    menuItem.target = nil
    menuItem.keyEquivalent = "M"
    menuItem.enabled = true
    mainMenu.addItem(menuItem)

    statusItem = statusBar.statusItemWithLength(-1)
    statusItem.menu = mainMenu
    statusItem.title = statusItem.menu?.itemAtIndex(0)?.title

}

It adds the item to menu, but it isn't enabled:

http://i68.fastpic.ru/big/2015/0116/39/8e444aa8fb6f113bcdad2753e915b439.jpeg

And the selector is valid too, the function setWindowVisible exists in the same class:

func setWindowVisible(sender : AnyObject?) {
    self.window!.orderFront(self)
}

回答1:

The target needs to be self instead of nil.

menuItem.target = self