我不知所措,为什么这是行不通的。菜单显示,但如果我将autoenablesItems保留为默认值,则该菜单将变灰,如果将其设置为false,则不会调用操作。

class GameScene: SKScene {
    // ...
    func action1(sender: AnyObject) {
        println("Urk, action 1")
    }

    func action2(sender: AnyObject) {
        println("Urk, action 2")
    }

    func popUpMenu(#event: NSEvent) {
        var theMenu = NSMenu(title: "Contextual menu")
        theMenu.addItemWithTitle("Action 1", action: Selector("action1:"), keyEquivalent: "")
        theMenu.addItemWithTitle("Action 2", action: Selector("action2:"), keyEquivalent: "")
        //theMenu.autoenablesItems = false
        NSMenu.popUpContextMenu(theMenu, withEvent:event, forView:self.view)
    }

    override func mouseDown(theEvent: NSEvent) {
        self.popUpMenu(event: theEvent) // The menu shows
    }
}

更新

按照@Chuck的回答,您将需要执行以下操作:
func popUpMenu(#event: NSEvent) {
    var theMenu = NSMenu(title: "Contextual menu")
    theMenu.addItemWithTitle("Action 1", action: Selector("action1:"), keyEquivalent: "")
    theMenu.addItemWithTitle("Action 2", action: Selector("action2:"), keyEquivalent: "")

    for item: AnyObject in theMenu.itemArray {
        if let menuItem = item as? NSMenuItem {
            menuItem.target = self
        }
    }

    NSMenu.popUpContextMenu(theMenu, withEvent:event, forView:self.view)
}

最佳答案

听起来您的问题是用该方法创建的NSMenuItem没有接收者,因此它使用了响应者链,并且此对象不在响应者链中。您可以通过将菜单项的目标设置为self来强制其看到您的对象。

10-08 08:05