Update NSMenuItem while the host menu is shown

后端 未结 1 565
面向向阳花
面向向阳花 2020-12-14 20:40

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

相关标签:
1条回答
  • 2020-12-14 21:15

    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];
    }
    
    0 讨论(0)
提交回复
热议问题