macOS-如何从“文件”菜单中删除“重复”,“移至”,“重命名”和“另存为”菜单项?

时间:2018-07-26 17:19:07

标签: macos cocoa nsdocument

我的基于文档的应用程序不需要这些项目,它们不在我的情节提要中。它们通过此调用链由系统插入。

-[NSMenu insertItem:atIndex:] ()
-[NSMenu insertItemWithTitle:action:keyEquivalent:atIndex:] ()
-[NSApplication(NSMenuUpdating) _customizeFileMenuIfNeeded] ()
-[NSApplication(NSMenuUpdating) _customizeMainMenu] ()
-[NSApplication finishLaunching] ()
-[NSApplication run] ()
  NSApplicationMain ()

2 个答案:

答案 0 :(得分:3)

先生的Swift 5变体。 fixit的答案将放置在NSApp委托的applicationDidFinishLaunching

if let fileMenu = NSApp.mainMenu?.items[1].submenu {
    for selector in [NSSelectorFromString("duplicateDocument:"),
                     NSSelectorFromString("moveDocument:"), 
                     NSSelectorFromString("renameDocument:"), 
                     NSSelectorFromString("saveDocumentAs:")] {
        let index = fileMenu.indexOfItem(withTarget: nil, andAction: selector)
        if index > -1 {
            fileMenu.removeItem(at: index)
        }
    }
}

答案 1 :(得分:1)

简单的方法是覆盖+[NSDocument autosavesInPlace]。但就我而言,我想要自动保存,因此我确实要重写该设置(返回YES),这给我留下了很辛苦的方法:

在我的应用程序委托的applicationDidFinishLaunching:中,我致电

- (void)removeUnwantedFileMenuItems
{
    NSMenu *fileMenu = NSApp.mainMenu.itemArray[1].submenu;

    void (^removeItemWithSelector)(SEL) = ^void(SEL selector) {
        NSInteger idx = [fileMenu indexOfItemWithTarget:nil andAction:selector];
        if (idx != -1)
        {
            [fileMenu removeItemAtIndex:idx];
        }
    };
    removeItemWithSelector(@selector(duplicateDocument:));
    removeItemWithSelector(@selector(moveDocument:));
    removeItemWithSelector(@selector(renameDocument:));
    removeItemWithSelector(@selector(saveDocumentAs:));
}