将NSOpenPanel选项传递给NSDocument

时间:2018-07-13 09:33:55

标签: macos cocoa

我知道如何将AccessoryView添加到NSOpenPanel(并且可以正常工作)。

现在,我想使用户在AccessoryView中选择的选项可用于打开的文档。

任何建议都可以做到(如果有的话)

1 个答案:

答案 0 :(得分:0)

我还没有找到标准的解决方案,所以我创建了自己的解决方案:

  • 在NSDocumentController中引入了一个字典,该字典将文件URL与选项集相关联
  • 重写runModalOpenPanel并使用以下步骤包装超级视图的runModalOpenPanel:首先设置附件视图,然后评估选项并将选项添加到字典中相关的URL。
  • 打开文档后,该文档可以-通过共享的NSDocumentController-访问字典并检索选项。

这个解决方案并没有让我震惊,但是我也看不到更简单的方法。

示例代码:

struct OptionsAtFileOpen {
    let alsoLoadFormat: Bool
}

class DocumentController: NSDocumentController {

    var fileOptions: Dictionary<URL, OptionsAtFileOpen> = [:]

    var accessoryViewController: OpenPanelAccessoryViewController!

    override func runModalOpenPanel(_ openPanel: NSOpenPanel, forTypes types: [String]?) -> Int {

        // Load accessory view
        let accessoryViewController = OpenPanelAccessoryViewController(nibName: NSNib.Name(rawValue: "OpenPanelAccessoryView"), bundle: nil)

        // Add accessory view and make sure it is shown
        openPanel.accessoryView = accessoryViewController.view
        openPanel.isAccessoryViewDisclosed = true

        // Run the dialog
        let result = super.runModalOpenPanel(openPanel, forTypes: types)

        // If not cancelled, add the files to open to the fileOptions dictionary
        if result == 1 {

            // Return the state of the checkbox that selects the loading of the formatting file
            let alsoLoadFormat = accessoryViewController.alsoLoadFormatFile.state == NSControl.StateValue.on

            for url in openPanel.urls {
                fileOptions[url] = OptionsAtFileOpen(alsoLoadFormat: alsoLoadFormat)
            }
        }

        return result
    }
}

然后在文档中

override func read(from data: Data, ofType typeName: String) throws {
    ...
    if let fileUrl = fileURL {
        if let dc = (NSDocumentController.shared as? DocumentController) {
            if let loadFormat = dc.fileOptions[fileUrl]?.alsoLoadFormat {
                ...
            }
        }
    }
}