获取状态菜单项的引用并更改其标题

时间:2013-09-10 11:38:58

标签: xcode cocoa

我有一个带有状态菜单的Mac OS应用程序(在Interface Builder中制作)。我想在特定事件发生时更改状态菜单项标题。我可以在动作处理程序中做得很好,因为我在那里引用了项目(sender):

- (IBAction)playPauseMusic:(id)sender {
  // ...
  [sender setTitle:@"New Title"];
}

但是如何在我的应用程序的其他部分执行此操作?我不知道如何在以下代码中引用menuItem

- (void) someOtherMethod:(int)isPlaying {
    menuItem = ...;
    if(isPlaying) {
        [menuItem setTitle:@"Pause"];
    }
}

如何做才能完成上述工作?

更新。以下是我添加状态菜单的方法:

// MyAppDelegate.h:

@interface MyApp : NSApplication
@end

@interface MyAppDelegate : NSObject <NSApplicationDelegate>
{
  NSMenu *statusMenu;
  NSStatusItem *statusItem;
  // ...
}
@property (strong) IBOutlet NSMenu *statusMenu;
// ...
@end

// MyAppDelegate.m:

@synthesize statusMenu;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    statusItem = [[NSStatusBar systemStatusBar]
        statusItemWithLength:NSVariableStatusItemLength];
    [statusItem setMenu:[self statusMenu]];
}

2 个答案:

答案 0 :(得分:2)

如果要访问菜单中的项目,请在菜单项上设置标签(例如,在IB中)并使用:

NSMenuItem *menuItem = [[statusItem menu] itemWithTag:100];    // 100 = example
menuItem.title = @"Something";

如果想要设置标题的代码与保存statusItem的对象不同,那么您需要公开执行上述代码的setStatusMenuTitle:forItemWithTag:方法。

但是,我无法告诉您如何在没有更多细节的情况下访问 对象。

答案 1 :(得分:1)

首先,我在Xcode 中为菜单项创建了一个插座。我按照"Create and connect a new outlet"视频指南进行了操作。我为我的菜单项创建了strong个出口:

@property (strong) IBOutlet NSMenuItem *playMenuItem;

然后将其添加到界面:

@interface MyAppDelegate ...
{
    // ...
    NSMenuItem *playMenuItem;
}

然后在实现中添加了@synthesize声明:

@synthesize playMenuItem;

最后,以下工作:

[playMenuItem setTitle:@"New Title"];

P.S。如果有人能告诉我如何让它变得更简单,我将不胜感激。