How to update NSMenu while it's open?

一个人想着一个人 提交于 2019-11-30 05:45:54

问题


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

回答1:


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.




回答2:


Updating the menu items in NSEventTrackingRunLoopMode solved this issue.




回答3:


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.




回答4:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!