Question

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!

Was it helpful?

Solution

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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top