swiftswift3nsmenuitem

Set state of NSMenuItem to On


I have created a menu bar app and I would like when you click on one of the menu bar items it toggles between the off state and the on state (ticked and unticked) but I am struggling to do this in code. Does anyone have any ideas about how this can be achieved?

I can see that I can set it in the Attributes Inspector but i would like to change it to On/Off once it has been pressed.

Thanks Miles


Solution

  • Simple solution: Create an IBAction

    @IBAction func toggleState(_ sender: NSMenuItem) {
        sender.state = sender.state == .on ? .off : .on
    }
    

    Connect the NSMenuItem to the IBAction. If the responding controller is not related to the Application Scene, connect the IBAction via First Responder (red cube)