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:
-
Define a
@State
property to hold a local copy of the trading entity:@State private var localTradingEntity: TradingEntity
-
Initialize the local trading entity with the passed entity in
init
:init(entity: TradingEntity) { self.localTradingEntity = entity }
-
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.
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 ...
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.
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 ...