I want to be able to access the UndoManager from inside my document model, so I can register undo actions from within the model:
// Assume I've extended MyDocument to conform to ReferenceFileDocument elsewhere...
final class MyDocument {
private var undoManager: UndoManager?
@Published var aNumber = 5 {
willSet {
if let undoManager = undoManager {
let currentValue = self.aNumber
undoManager.registerUndo(withTarget: self) { target in
target.aNumber = currentValue
}
}
}
}
func setUndoManager(undoManager: UndoManager?) {
self.undoManager = undoManager
}
}
To be register the undoManager, I have tried this:
struct DocumentView: View {
let document : MyDocument
@Environment(\.undoManager) var undoManager
var body: some View {
MyDocumentEditor(document: document)
.onAppear {
document.setUndoManager(undoManager: undoManager)
}
}
}
When running my app and loading a saved document this works. But when starting from a new document the UndoManager is nil.
I've tried things like:
@Environment(\.undoManager) var undoManager {
didSet {
self.document.setUndoManager(undoManager: undoManager)
}
}
My objective here is to try and keep as much logic in the model and the views focusing only on UI stuff as much as possible. I wish that ReferenceFileDocument gave a property to access its associated UndoManager as is available with NSDocument.