Connecting Multiple NSMenuItems with Actions and State Variables

陌路散爱 提交于 2019-12-06 13:35:59

问题


I'm not sure how to describe what I need but I'll give it a try, via an example :

Let's say we have a window and a sidebar, and want to toggle it (I mean the sidebar : on/off).

Now, let's also say that :

  • The user may toggle the sidebar via an item at the Main menu (e.g. Show Sidebar / Hide Sidebar)
  • The user may also toggle the sidebar via a button
  • And there is also another item, in some other menu, to do the very same thing (Show/Hide Sidebar)

What would be the most practical Cocoa-friendly approach to achieve that?

Of course, that means that, e.g. :

  • When somebody clicks the button, apart from the sidebar (showing or hiding), the menu items must now be showing the current status of the sidebar (e.g. "Show sidebar" must now turn to "Hide Sidebar" in all possible instances within menus, etc)

I hope you get the idea; it's definitely not something difficult; but I'm definitely confused on how I could use all of Cocoa's tricks to do it fast.

Thanks!


回答1:


I'm assuming you have some controller object which implements an action -toggleSidebar:, and that both menus target the same controller. Also, in the controller, you keep an instance variable BOOL isSidebarShown.

Make your controller implement the NSUserInterfaceValidations protocol. Something like this:

- (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)anItem
{
    if (anItem.action == @selector(toggleSidebar:) && [anItem isKindOfClass:[NSMenuItem class]])
    {
        NSString* title = isSidebarShown ? @"Hide Sidebar" : @"Show Sidebar";
        [(NSMenuItem*)anItem setTitle:title];
    }

    return YES;  // either way, the menu item is enabled
}


来源:https://stackoverflow.com/questions/9764179/connecting-multiple-nsmenuitems-with-actions-and-state-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!