Document based app using one single window

225 views Asked by At

I have a document-based macOS application, which is a basic text editor. The default behavior is to create a new window for every opened document. But I want to only have one window displayed at a time and when opening a document or creating a new one, this should happen in the same window and thus replace the old document.

I've tried to do some hacking in the makeWindowControllers method from NSDocument by not instantiating a new window controller but reusing an old one. But after some problems with this approach, I figured this is not the right way to go. I was wondering if there is a common approach to this problem.

This is the code I've tried

class Document: NSDocument {
    
    static var sharedWindow: NSWindowController?
    
    override func makeWindowControllers() {
        // Instaniate window controller there is none
        if Document.sharedWindow == nil {
            // Returns the Storyboard that contains your Document window.
            let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: nil)
            Document.sharedWindow = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("Document Window Controller")) as? NSWindowController
        }

        guard let sharedWindow = Document.sharedWindow else { return }
        if let previousDocument = sharedWindow.document as? NSDocument {
            previousDocument.close()
        }

        self.addWindowController(sharedWindow)

        sharedWindow.contentViewController?.representedObject = content
        (sharedWindow.contentViewController as? ViewController)?.handleOpenDocumentOperation()
    }

    ...
}
0

There are 0 answers