سؤال

I am working on a Cocoa document based application. I have a menu item in the file menu named "Export Things…". This menu item is connected to the first responder, and calls a selector in MyDocument. So far so good.

I would like to change the title of this menu item depending on user selection. If the user has nothing selected, it should read "Export All Things…", when the user has some things selected it should read "Export Selected Things…". When no document is open, it should just read "Export Things…".

Where and when should I change this menu item? I figure I can just change the menu item using setTitle:, but how do I get a reference to the NSMenuItem?

هل كانت مفيدة؟

المحلول

You can implement -validateMenuItem: in the responder class that handles the menu item's action. It should return a BOOL (which indicates whether the item is enabled), but you also get a reference to the NSMenuItem as a parameter that you can use to change the title.

To decide which menu item you're dealing with, you should inspect its action, e.g.

- (BOOL)validateMenuItem:(NSMenuItem *)item {
  if ([item action] == @selector(export:)) {
    if (hasSelection) {
      [item setTitle:NSLocalizedString(@"Export Selected Things",nil)];
    } else {
      [item setTitle:NSLocalizedString(@"Export All Things",nil)];
    }
  }
  return YES;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top