【发布时间】:2013-11-10 03:22:25
【问题描述】:
我的应用有一个由 .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:)];
}
}
我的问题是,这是实现这一目标的正确/最聪明/最优雅的方式吗?我的意思是,这在可可应用程序中是非常标准的行为(参见 Numbers 的“Inspector”),其他人是如何做到的?
改进它的一种方法是避免将菜单项恢复为其原始标题/操作的代码重复。此外,理想情况下,我会将标题字符串替换为对NSLocalizedString() 的调用。但也许还有一种我不知道的更优雅、更标准的方法......
【问题讨论】:
-
>May app has an... 我猜他的意思是 My app has an。我花了半分钟才通过第一句话。
标签: objective-c cocoa toggle nswindowcontroller nsmenu