3

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

Miles.Kelly
  • 101
  • 9

2 Answers2

6

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)

vadian
  • 274,689
  • 30
  • 353
  • 361
  • Exactly what i was looking for amazing, thank you! I am assuming that when each state is toggled I can call a different function to action on each toggle state? – Miles.Kelly Aug 02 '17 at 08:14
  • You can call the *different function* right after the line to set the state. Actually Charles` answer is much better if the menu item is directly related to the scene / controller – so the value can be bound. In this case add the `didSet` observer and call your *different function* in there. – vadian Aug 02 '17 at 08:24
3

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.

Charles Srstka
  • 16,665
  • 3
  • 34
  • 60