After Paul's fun HWS+ stream in which he showed us how to do a simple drawing app in SwiftUI, I started looking at adding Undo support to one of my own applications. I've done it before, but it was ugly and I am really interested in using the right idiom and being much more Swifty about it.
I Learned A Thing and I thought I'd share. In the TinyDraw app, we were targeting iOS, while my application is targeting macOS primarily. So that's maybe where the difference lies. Anyway, I added the UndoManager to my main view, and assigned it to my model where the modifications are happening in an onAppear
block. However, I noticed that when I made modifications to the model, the UndoManager was nil! I added some print lines to help me figure this out:
.onChange(of: undoManager) { newManager in
print("UndoManager changed!")
if newManager != nil {
print("The new manager is not nil!")
} else {
print("The new manager is nil!")
}
document.scenario.undoManager = newManager
}
.onAppear {
if undoManager != nil {
print("Got an UndoManager on appear")
} else {
print("This view appeared with no UndoManager!")
}
document.scenario.undoManager = undoManager
}
It turns out that when the main view first appears, the undoManager is nil. Immediately afterward, it gets set. So my debugger log looks like this:
This view appeared with no UndoManager! UndoManager changed! The new manager is not nil!
So, hey, FYI, you might need to have an onChange
block if you want to be sure you get the UndoManager.