Connecting Multiple NSMenuItems with Actions and State Variables

天涯浪子 提交于 2019-12-04 19:06:46

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