Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMenu selector in Swift

Tags:

swift

I'm at a loss to see why this doesn't work. The menu shows, but is grayed out if I leave autoenablesItems at the default, and the actions aren't called if I set it 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
    }
}

Update

As per @Chuck's answer, you will need to do the following:

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)
}
like image 232
Grimxn Avatar asked Jun 23 '14 18:06

Grimxn


1 Answers

It sounds like your problem is that an NSMenuItem created with that method doesn't have a receiver, so it uses the responder chain, and this object is not in the responder chain. You can force it to see your object by setting the menu items' targets to self.

like image 166
Chuck Avatar answered Jan 03 '23 23:01

Chuck