How to handle undo of model properties bound to UI elements?

I have a macOS application using SwiftUI, with a ReferenceFileDocument object. I have properties that can be bound to a UI element, such as a toggle, and they change fine, but I haven't worked out how to get undo to work for these (I can do it for more complex changes when I can call into the model code and register the undo).

I implemented the approach from https://lostmoa.com/blog/HandlingUndoAndRedoInSwiftUI/, and it seems to me that the undoManager keeps getting changed. If I put in a breakpoint in the onChange and print out the new undoManager, it is set when the view appears, and then set to a different value when the checkbox is clicked. So the undo gets lost and not sent to the undoManager which is in the environment from the document.

I may well be missing something obvious here. Is there a way to fix this, or a better approach?

Post not yet marked as solved Up vote post of Mussau Down vote post of Mussau
577 views