处理NSMenuDelegate menuWillOpen以更改目标 [英] Handling NSMenuDelegate menuWillOpen for changing targets

查看:108
本文介绍了处理NSMenuDelegate menuWillOpen以更改目标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多有关使用menuWillOpen的答案.他们都解释说,首先需要设置菜单的代表.

There are lots of related answers about using menuWillOpen. They all explain that one needs to set the menu's delegate first.

当我只有一个目标(例如首选项"窗口或主应用程序)时,这很容易.

This is easy when I have just one target, like a Preferences window or the main application.

但是如果我有一个基于文档的应用程序,并且我需要活动文档句柄menuWillOpen怎么办?然后委托不再是常量.

But what if I have a document based app, and I need to have the active document handle menuWillOpen? Then the delegate isn't a constant any more.

处理此问题的正确方法是什么?我是否必须将委托设置为单个对象(如AppDelegate),然后将调用转发到活动视图控制器(但如何正确完成)?还是还有其他优雅的方式?

What's the proper way to handle this? Do I have to set the delegate to a single object (like the AppDelegate) and then forward the call to the active view controller (but how is that done correctly)? Or is there some other elegant way?

推荐答案

我想出了这个似乎可行的代码:

I came up with this code which appears to work:

// This is in my AppDelegate class, and the NSMenu's delegate points to it:
- (void)menuWillOpen:(NSMenu *)menu {
    // Forward to active document controller
    NSWindow *mainWindow = [NSApplication sharedApplication].mainWindow;
    NSResponder *r = mainWindow.firstResponder;
    while (r) {
        if ([r respondsToSelector:_cmd]) {
            [(id<NSMenuDelegate>)r menuWillOpen:menu];
            return;
        }
        r = r.nextResponder;
    }
}

假定响应者链下的控制器实现了menuWillOpen:

It assumes that a controller down the responder chain implements menuWillOpen:

这篇关于处理NSMenuDelegate menuWillOpen以更改目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆