Handling NSMenuDelegate menuWillOpen for changing targets

心不动则不痛 提交于 2019-12-24 23:25:40

问题


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.

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.

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?


回答1:


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;
    }
}

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



来源:https://stackoverflow.com/questions/55987213/handling-nsmenudelegate-menuwillopen-for-changing-targets

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