UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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.

4      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.