Why is my NSMenuItem is disabled when it has an action?

397 Views Asked by At

I'm implementing a custom NSToolbarItem that has a button and a dropdown, like Mail. The only thing that's not working, though, is that the NSMenuItem is disabled. Whatever I do, I can't get it enabled. Any idea what I'm doing wrong here?

class DropdownTypeToolbarItem: NSToolbarItem {
    private var handler: ((NSNumber) -> Void)?

    init(itemIdentifier: NSToolbarItem.Identifier, handler: ((NSNumber) -> Void)?) {
        super.init(itemIdentifier: itemIdentifier)

        self.handler = handler

        let control = NSSegmentedControl(labels: ["Open", ""],
                                         trackingMode: .momentary,
                                         target: self,
                                         action: #selector(open))

        let menu = NSMenu(title: "")
        menu.addItem(withTitle: "Export", action: #selector(export(_:)), keyEquivalent: "")

        control.setMenu(menu, forSegment: 1)
        control.setShowsMenuIndicator(true, forSegment: 1)

        self.view = control
    }

    @objc func open() {
        print("select open")
        self.handler?(0)
    }

    @objc func export(_ sender: Any) {
        print("select export")
        self.handler?(1)
    }
}
1

There are 1 best solutions below

0
seth On

The NSToolbarItem itself is not part of the responder chain, which is what's used to determine if the menu item can be enabled, when the target of the menu item is nil. In this case, you should just explicitly set the target of the menu iem to be the toolbar item.