我的应用程序有一个由 .xib 文件和自定义窗口控制器类定义的“检查器”面板:AdjustmentsWindow.xib
和AdjustmentsWindowController.m
.
I want to have a Window -> Show Adjustments
menu item in the application's main menu bar, that when selected will show the adjustments window. 我将 NSObject 实例放入包含主菜单的 xib 中,并将其类更改为“AdjustmentsWindowController”。我还将菜单项action
与控制器的-showWindow:
方法挂钩。到目前为止一切顺利:窗口控制器在应用程序启动时被实例化,当您选择菜单项时,它会显示其窗口。
但是当窗口已经可见(有效地切换可见性)时,我希望相同的菜单项兼作“隐藏调整”。所以这就是我所做的:
调整窗口控制器.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:)];
}
}
我的问题是,这是实现这一目标的正确/最聪明/最优雅的方式吗?我的意思是,这是可可应用程序中非常标准的行为(参见 Numbers 的“Inspector”),其他人是如何做到的?
改进它的一种方法是避免将菜单项恢复为其原始标题/操作的代码重复。此外,理想情况下,我会用调用来替换标题字符串NSLocalizedString()
。但也许有一种我不知道的更优雅、更标准的方法......