Getting a particular menu item from MainMenu

时光怂恿深爱的人放手 提交于 2019-12-24 02:42:45

问题


I have a nib (winA.xib) that contains a window. My app delegate contains an NSWindowController subclass called WinAController.

WinAController has a property (NSMenu *mainMenu) that I want to point to the MainMenu. I have set it after I instantiate WinAController with this code:

    WinAController = [[WinAController alloc] initWithWindowNibName:@"WinA"];
    WinAController.mainMenu = [NSApp mainMenu];

I have a menu item underneath the "Window" top-level menu item on MainMenu that invokes the [WinAController showWindow] method and displays WinA. I want to toggle the on/off state of this menu item depending on whether WinA is visible or not. WinAController also has another property (NSMenuItem *myMenuItem).

How can I get a reference to a sub menu of the "Window" top-level menu item. The title of sub menu item I want to get is "Command". I have tried this:

    if (mainMenu != nil) {
    myMenuItem = [mainMenu itemAtIndex:[mainMenu indexOfItemWithTitle:@"Command"]];
}

But it doesn't seem to work.

Where am I going wrong?

Thanks,

Edit: I have now placed WinAController in mainMenu.xib. I have set WinA's (in winA.xib) File's Owner to be of class WinAController but I can't figure out how to hook up WinAController's window IBOutlet to WinA as they are in different nibs!


回答1:


I thought I told you to put the Window Controllers in MainMenu.xib?

Oh well, nothing ventured, nothing gained. What you want to do, of course, is the following:

@interface MyApplicationDelegate : NSObject {
  IBOutlet NSMenuItem *winAMenuItem;
}

@property(assign) IBOutlet NSMenuItem *winAMenuItem;

@end

Then you can access this through [[NSApp delegate] winAMenuItem];




回答2:


You can store a reference to your menu item directly, possibly via IBOutlet in your main nib.

Or (better, IMO), you can implement -validateMenuItem: in WinAController and set the state there (that way, the state is only set when the user will actually see it, too):

- (BOOL)validateMenuItem:(NSMenuItem *)item {
    if ([item action] == @selector(showWindow:)]
        [item setState:[winA isVisible] ? NSOnState : NSOffState];

    return YES;
}


来源:https://stackoverflow.com/questions/2869424/getting-a-particular-menu-item-from-mainmenu

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