显示主机菜单时更新NSMenuItem [英] Update NSMenuItem while the host menu is shown
问题描述
我有一个 NSMenuItem
,我需要更新以显示进度(如Time Machine做它的备份)。问题是当我在 NSMenuItem
和 title 上设置新的
title
code>不会改变。
当我关闭并重新打开菜单时,实际上正在更改,但我想在用户查看时更新它。
我也尝试删除一个项目并重新插入它没有结果。
任何指针?
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];
}
I have an NSMenuItem
that I need to update to show a progress (like Time machine does with it's backup). The problem is that when I set a new title
on that NSMenuItem
and the title
is not changing.
It is in fact changing when I close and reopen the menu, but I want to update it while the user is looking at it.
I also tried remove an item and re-inserting it with no result.
Any pointers?
This actually works with no additional effort if your updating code runs in the run loop mode which is used during menu tracking. This is NSEventTrackingRunLoopMode
, but you probably just want to use NSRunLoopCommonModes
so the menu item title is correct when the menu is pulled down.
Here's a simple example of a menu item foo
that counts the number of seconds since the app launched:
- (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];
}
这篇关于显示主机菜单时更新NSMenuItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!