问题
I have a menu item "foobar" that i need to enable on my main window (app delegate), but disable on all other windows. I'd like to know how to do that, because the first responder business is very confusing to me. Here's what i have now:
- "foobar" item is connected to first responder's "foobar:" custom action in MainMenu.xib
- there is a "foobar:" action in the main app delegate so the menu item is enabled and works
- now i load and "makeKeyAndOrderFront" another window
- i focus some control on that new window
- this is the place where my "foobar" item should be disabled, but it's not
I can see that the "validateMenuItem" is being called in the app delegate, but it's not being called in the second window's controller.
Could someone explain it to me in very simple terms why this is happening and what options i have to solve this?
Thanks for your thoughts
回答1:
Set your app delegate as delegate of the main window, and implement these method:
- (void)windowDidBecomeKey:(NSNotification *)notification
{
[foobar setEnabled: YES];
}
- (void)windowDidResignKey:(NSNotification *)notification
{
[foobar setEnabled: NO];
}
About first responder
The first responder is a NSControl that is inside the window.For example on a particular window you have two text fields: textField1 and textField2.When you type the input goes just to the first responder (one between all the controls that accept the first responder).So what you need is to know which window is key, you don't need to know who is the first responder in your specific case.
EDIT
There is also another (maybe faster, but depends on personal preferences) way to do it: through interface builder, select the menu item that you want to make enabled only when a certain window is key.Let's suppose that this window is an ivar of the app delegate named window1.Then click on that menu item, go to the bindings inspector, under "enabled" select bind to: app delegate, model key path: self.window.isKeyWindow.
A little image hint:
来源:https://stackoverflow.com/questions/13976298/cocoa-validate-menu-items-in-multiple-windows