How to update NSMenu while it's open?

ぐ巨炮叔叔 提交于 2019-11-30 20:43:13

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.

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