Connecting NSMenuItems with Actions & vice versa
-
26-05-2021 - |
Question
Let me explain what I mean :
Let's say we have a menu with several items in it (let's say it's a... collection of options, only one of which may be enabled at any time).
What is the suggested implementation (bindings? I don't know...), so that I could satisfy the scenarios below :
The user clicks an item on the menu, and this triggers the action
doSomething
on some controller. Also, when the actiondoSomething
is called independently, the appropriate menu item should be checked, as well.We have an identical menu (somewhere else) with the same options as the initial menu. The user clicks on an item of menu A, the same item is checked on menu B, the action
doSomething
is performed. This should work in any order of actions (A->B->action, B->A->action, action->A->B)
Solution
-doSomething:
should set a BOOL
variable indicating whether or not the menu items should be checked.
The, use the NSUserInterfaceValidations
protocol, just as I explained in an answer to your previous question.
In -validateUserInterfaceItem:
, get the value of that BOOL
, then:
[(NSMenuItem*)anItem setState:(boolValue ? NSOnState : NSOffState)];
OTHER TIPS
I would have each menu item call its own action method, have each action method set an instance variable to a value depending on which one it is and them implement the method for the NSMenuValidation informal protocol, and us that to update the menu item to show its check mark as well as the usual enable/disable.