以编程方式添加“打开最近的”菜单到上下文弹出菜单

发布于 2024-12-01 06:30:38 字数 416 浏览 0 评论 0原文

我有一个带有菜单栏图标和状态菜单的非文档 Cocoa 应用程序。我在 Interface Builder 的状态菜单中添加了一个“打开最近打开的”菜单。填充菜单效果很好:

[[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:
            [NSURL fileURLWithPath:filename]]

现在我还想在上下文弹出菜单中添加第二个“打开最近的”菜单。我将如何以编程方式创建菜单,以便它像状态菜单中的版本一样自动填充条目?

我尝试在状态菜单中创建该副本,但它没有被填充。我假设 NSDocumentController 不知道菜单(坦率地说,我不知道它如何知道状态菜单中的菜单)。

I have a non-document Cocoa application with a menubar icon and status menu. I've added an "Open Recent" menu to the status menu in Interface Builder. Populating the menu works just fine:

[[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:
            [NSURL fileURLWithPath:filename]]

Now I would also like to add a second "Open Recent" menu to a context popup menu. How would I create the menu programmatically so that it gets populated with entries automatically as it does for the version in the status menu?

I tried creating a copy of the one in the status menu, but it does not get populated. I assume that NSDocumentController is not aware of the menu (frankly, I don't know how it knows about the one in the status menu).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

听闻余生 2024-12-08 06:30:38

作为参考,我发现的关于“打开最近的”菜单内部工作原理的最佳文档是:
http:// lapcatsoftware.com/blog/2007/07/10/working-without-a-nib-part-5-open-recent-menu/

不幸的是,这对此没有多大帮助,因为即使您像这样创建菜单,它会被NSDocumentController忽略。在 applicationDidFinishLaunching: 调用之前,菜单必须存在于主菜单中,否则将不会被选取 - 因此,重复的菜单也会被忽略。

我最终所做的以及到目前为止似乎有效的事情是:

第一个想法是从主菜单中选择相应的 NSMenu 并将其附加到其他菜单中,希望引用计数将使这项工作成功。没有这样的运气,如果子菜单已经在另一个 NSMenuItem 中,setSubmenu 就会抛出异常。

因此,我“重新设置”子菜单的父级 - 当我需要在另一个菜单中显示它时,我将其从主菜单的打开最近项目中删除,并将其设置为新菜单中的子菜单。后来我把它移回来。当然,这是一个丑陋的黑客行为,但它完成了工作。

For reference, the best documentation on the inner workings of the Open Recent menu that I found is this:
http://lapcatsoftware.com/blog/2007/07/10/working-without-a-nib-part-5-open-recent-menu/

Unfortunately, it doesn’t help much with this, because even if you create the menu like this, it will be ignored by NSDocumentController. The menu must exist in the main menu before applicationDidFinishLaunching: call, otherwise it won’t be picked up — and consequently, duplicate ones are ignored too.

What I ended up doing, and what seems to work so far, is this:

The first idea was to pick the corresponding NSMenu from the main menu and attach it into other menus as well, hoping that reference counting will make this work. No such luck, setSubmenu throws if the submenu is already in another NSMenuItem.

So I “reparent” the submenu instead — when I need to show it in another menu, I remove it from the main menu’s Open Recent item and set it as submenu in the new menu. Later, I move it back. It’s an ugly hack, of course, but it gets the job done.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文