I have a NSMenu with dynamically added NSMenuItems. The NSMenu is not refreshing properly while it's kept open. I am calling NSMenu update method in NSEventTrackingRunLoopModes
.
I have implemented following methods to update NSMenu.
- (void)menuNeedsUpdate:(NSMenu *)menu {
for (NSInteger index = 0; index < count; index++)
[self menu:menu updateItem:[menu itemAtIndex:index]
atIndex:index
shouldCancel:NO];
}
- (BOOL)menu:(NSMenu *)menu updateItem:(NSMenuItem *)item atIndex:(NSInteger)index shouldCancel:(BOOL)shouldCancel`
- (NSInteger)numberOfItemsInMenu:(NSMenu *)menu
I am dynamically populating menu items in a timer and NSMenu is not updating while it's open.
Make sure to have the timer fire on the respective run mode:
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
You might only have it fire on NSDefaultRunLoopMode
right now.
Updating the menu items in NSEventTrackingRunLoopMode
solved this issue.
You have left out a bunch of the code. However, you aren't supposed to call -menu:updateItem:atIndex:shouldCancel:
. That's a method that you're supposed to implement and the framework is supposed to call it.
Also, generally you're only suppose to implement either -menuNeedsUpdate:
or both of -numberOfItemsInMenu:
and -menu:updateItem:atIndex:shouldCancel:
. Implementing all three doesn't make much sense. You implement the former if you can build the menu immediately. You implement the latter two if building the menu will take some time.
Finally, all of those methods are documented as being called "when a menu is about to be displayed". I'm not terribly surprised that they're not called repeatedly while the menu is open.
If you know the menu needs to be updated, you can try invoking -[NSMenu update]
. That may provoke it to call your delegate methods. I'm pretty sure you can also just call the methods on NSMenu
and NSMenuItem
to modify the menu, without waiting for your delegate to be called.
Live updating may not be possible with a regular menu. It is listed as an advantage of JGMenuWindow over NSMenu.
来源:https://stackoverflow.com/questions/10136692/how-to-update-nsmenu-while-its-open