显示主机菜单时更新NSMenuItem



我有一个NSMenuItem,我需要更新它来显示进度(就像Time machine处理它的备份一样)。问题是,当我在NSMenuItem上设置新的title时,title没有改变。

事实上,当我关闭并重新打开菜单时,它正在发生变化,但我想在用户查看时更新它。

我还尝试删除一个项目并重新插入,但没有结果。

有指针吗?

如果您的更新代码在菜单跟踪期间使用的运行循环模式下运行,那么这实际上不需要额外的工作。这是NSEventTrackingRunLoopMode,但您可能只想使用NSRunLoopCommonModes,以便在下拉菜单时菜单项标题是正确的。

下面是一个菜单项foo的简单示例,它统计应用程序启动后的秒数:

- (void)doStuff;
{
    static int i = 0;
    [foo setTitle:[NSString stringWithFormat:@"%d", ++i]];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification;
{
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:
                                [self methodSignatureForSelector:@selector(doStuff)]];
    [invocation setTarget:self];
    [invocation setSelector:@selector(doStuff)];
    [[NSRunLoop mainRunLoop] addTimer:[NSTimer timerWithTimeInterval:1 invocation:invocation repeats:YES] forMode:NSRunLoopCommonModes];
}

最新更新