TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

UndoManager, TinyDraw (HWS+), and View.onAppear

Forums > macOS

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.


Hacking with Swift is sponsored by Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.