【问题标题】:Document-based app's 'New Document' dock menu item won't open new document基于文档的应用程序的“新文档”停靠菜单项不会打开新文档
【发布时间】:2015-08-23 11:14:34
【问题描述】:

我的基于文档的应用程序有一个带有“新文档”项的停靠菜单。停靠菜单是在 Interface Builder 中制作的,其项目的操作连接到 'First Responder's -newDocument:

文档控制器是NSDocumentController 的子类,称为DocumentController

在应用程序委托中,此代码用于防止在启动时打开无标题文档(而不是显示文档控制器的打开面板):

- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender {

    [(DocumentController *)[NSDocumentController sharedDocumentController] openDocument:self];
    return NO;

}

如果我现在启动我的应用程序,它将显示打开的面板而不是无标题的文档。如果我然后单击停靠菜单的“新建文档”项,则不会打开新文档。如果我在模板主菜单中单击标准文件菜单选项“新建文档”,则会打开一个新文档。

我想不出为什么会这样,你可以吗?如何让停靠菜单打开新文档?


编辑:Here is a sample project which has no NSDocumentController subclass but still has the same problem.

【问题讨论】:

    标签: objective-c cocoa nsdocument nsmenu nsdocumentcontroller


    【解决方案1】:

    菜单项调用文档控制器上的 newDocument 方法。如果您单击停靠栏,您会触发 NSApplication 的东西并且它是委托的。例如。如果您有一个现有的应用程序窗口,那么您将不会在那里被调用。没有窗口会触发 applicationShouldOpenUntitledFile

    在您的文档控制器中重写如下:

    - (id)openUntitledDocumentAndDisplay:(BOOL)displayDocument error:(NSError *__autoreleasing *)outError {
      [self openDocument:nil]
    }
    

    如果您希望在启动后显示 openPanel,而不是响应 appdelegate(应该 bla bla)。如果您想在用户单击图标时触发它,请执行第二种方法

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        [(DocumentController *)[NSDocumentController sharedDocumentController] openDocument:nil];
    }
    
    - (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender {
        return YES;
    }
    

    文件菜单的新建项目在基于文档的应用程序中的操作。此方法的默认实现调用 -openUntitledDocumentAndDisplay:error: 如果返回 nil,则在应用程序模式面板中显示错误。

    • (IBAction)newDocument:(id)sender;

    【讨论】:

    • 每次用户想要创建新文档时都会打开打开的面板。我想要实现的是在启动时显示一个打开的面板,然后用户可以在我的停靠栏或文件菜单中单击“新建文档”来创建一个无标题的文档(同时打开的面板消失)。一切正常,除了停靠菜单 - 出于某种原因,它从不调用 -newDocument:
    • 您的示例项目有效。我单击停靠图标并点击新文档-> 它会打开新文档窗口。当显示打开的面板时,它不会打开新窗口,因为您处于不同的运行循环(openpanel 的运行循环)中。
    • 感谢您的帮助,当显示打开的面板时,“文件 > 新文档”项可以工作,但我放在 Dock 中的等效图标没有,这是因为运行循环不同吗?
    • 在打开文档后使用 [NSApp stopModal] + 从菜单中调用新文档。
    • 如果您希望您的代码正常工作,请不要在“applicationShouldOpenUntitledFile”中调用 openDocument。根本不要在应用程序委托中调用它。如果您想获得书面行为,请子类 nsdocumentcontroller。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多