Nic*_*ari 3 cocoa objective-c nsmenu toggle nswindowcontroller
我的应用程序有一个'inspector'面板,由.xib文件和自定义窗口控制器类定义:AdjustmentsWindow.xib和AdjustmentsWindowController.m.
我想Window -> Show Adjustments在应用程序的主菜单栏中有一个菜单项,选中后将显示调整窗口.我将NSObject实例放入包含主菜单的xib中,并将其类更改为"AdjustmentsWindowController".我还将菜单项连接action到控制器的-showWindow:方法.到目前为止一切顺利:窗口控制器在应用程序启动时实例化,当您选择菜单项时,它会显示其窗口.
但是,当窗口已经可见时,我想让相同的菜单项加倍为"隐藏调整"(有效地切换可见性).所以这就是我所做的:
AdjustmentsWindowController.m:
- (void) windowDidLoad
{
[super windowDidLoad];
[[self window] setDelegate:self];
}
- (void) showWindow:(id)sender
{
// (Sent by 'original' menu item or 'restored' menu item)
[super showWindow:sender];
// Modify menu item:
NSMenuItem* item = (NSMenuItem*) sender;
[item setTitle:@"Hide Adjustments"];
[item setAction:@selector(hideWindow:)];
}
- (void) hideWindow:(id) sender
{
// (Sent by 'modified' menu item)
NSMenuItem* item = (NSMenuItem*) sender;
// Modify back to original state:
[item setTitle:@"Show Adjustments"];
[item setAction:@selector(showWindow:)];
[self close];
}
- (void) windowWillClose:(NSNotification *)notification
{
// (Sent when user manually closes window)
NSMenu* menu = [[NSApplication sharedApplication] mainMenu];
// Find menu item and restore to its original state
NSMenuItem* windowItem = [menu itemWithTitle:@"Window"];
if ([windowItem hasSubmenu]) {
NSMenu* submenu = [windowItem submenu];
NSMenuItem* item = [submenu itemWithTitle:@"Hide Adjustments"];
[item setTitle:@"Show Adjustments"];
[item setAction:@selector(showWindow:)];
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,这是实现这一目标的正确/最聪明/最优雅的方式吗?我的意思是,这是可可应用程序中相当标准的行为(参见Numbers""Inspector"),其他人如何做到这一点?
改进它的一种方法是避免将菜单项恢复到其原始标题/动作的代码重复.另外,理想情况下我会用调用替换标题字符串NSLocalizedString().但也许有一种更优雅,标准的方法,我不知道......