Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 579
Miles.Kelly Avatar asked Sep 14 '25 07:09

Miles.Kelly


2 Answers

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)

like image 107
vadian Avatar answered Sep 16 '25 07:09

vadian


Simplest and easiest way to do it with almost no code:

  1. Create a boolean property on your app delegate (it can be on another object if that's more appropriate), and mark it with '@objc' and 'dynamic' like so:

@objc dynamic var foo: Bool = false

  1. In Interface Builder, click on your menu item, and go to the Bindings inspector. Bind 'value' to App Delegate, leave Controller Key blank, and set Model Key Path to the name of the property (in this case, 'foo').

  2. There is no step three.

like image 26
Charles Srstka Avatar answered Sep 16 '25 07:09

Charles Srstka