Change document in open window in macOS app

穿精又带淫゛_ 提交于 2021-02-05 12:29:51

问题


I am writing a document-based application for macOS. I am trying to write a feature that changes the active document in the current window (in order to be able to cycle through the next/previous documents in a folder, the way one can do with image-browser apps).

What command should I be calling to open a different document in the current window? The documentation suggests that openDocument might do this, but when I run

documentController.openDocument(nextFile!)

then I just get an NSOpenPanel which opens a new document in a separate window. How can I open a different document in the current window - with a URL I specify in coding, rather than through an OpenPanel?


回答1:


You can't open a document in the window of another document. Instead of

NSDocumentController -> document -> window

do it the other way around

app delegate -> window/view -> document.

The window is owned by the app delegate or a controller and the view controller of the window owns the document. The document is created with

convenience init(contentsOf url: URL, ofType typeName: String) throws

Edit:

The documentation of addWindowController(_:) of NSDocument suggests that it's possible to replace the document of a window controller:

You cannot attach a window controller to more than one document at a time. The default implementation of this method removes the passed-in window controller from the document to which it is attached, if it is already attached to one, then sends it a document message with self as the argument. It also ignores redundant invocations.

and yes, it does work in my test app:

let prevDocument = windowController.document
let newDocument = Document(contentsOf: newURL, ofType: myDocumentType) // add do-catch
NSDocumentController.shared.addDocument(newDocument);
newDocument.addWindowController(windowController)
prevDocument.close()


来源:https://stackoverflow.com/questions/57759693/change-document-in-open-window-in-macos-app

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