[Solved] How do I implement Undo & Redo in SwiftUI using SwiftData in iOS17 Beta 4+ – Swiftui

by
Ali Hasan
swift-data swiftui-animation undo-redo

Quick Fix: Prioritize overall trading entity rather than each character on it’s name. Update the trading entity and ensure that name is copied to it on pressing submit.

The Problem:

In SwiftUI with SwiftData library and Core Data, how can undo and redo functionality be effectively implemented for user entry forms in iOS 17 Beta 4+ such that changes made to the form fields can be reversed and restored with a button click, similar to the undo/redo functionality available with the device shake gesture or keyboard buttons, but without the confirmation dialog?

The Solutions:

Solution 1: Update Values On Submit

The undo operation doesn’t perform the expected changes because it’s undoing every keystroke on the TextField. To have it undo the submitted value, you need to update the entity with the final value only when the user presses submit.

Here’s how to do it:

  1. Define a @State property to hold a local copy of the trading entity:

    @State private var localTradingEntity: TradingEntity
    
  2. Initialize the local trading entity with the passed entity in init:

     init(entity: TradingEntity) {
         self.localTradingEntity = entity
     }
    
  3. In the body of the view, use the local trading entity for the TextField and add an .onSubmit modifier to update the entity when the user presses submit:

    VStack(spacing: 12) {
        LabeledContent("Name") {
            TextField("required", text: $localTradingEntity.name)
                .onSubmit {
                    tradingEntity = localTradingEntity
                }
        }
    }
    

This way, the undo operation will undo the submitted value instead of every keystroke.

Q&A

How undo works with SwiftData?

Undo manager undoes every change on TradingEntity, including each keystroke on a TextField.

How to undo only final submitted value?

Use a local copy of the entity in your state, and copy values from local to actual entity when submitting.

Video Explanation:

The following video, titled "Solving Equations with Undo Tables - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Algebra can be hard! In this video, I show you how you can use an Undo Table to understand an algebra equation and figure out how to solve ...