In my multiplatform SwiftUI document app, where should I implement undo? In the Views with Forms and Lists, Bindings, data classes or somewhere else? I am now implementing undo in Bindings and Lists, but I'm wondering if that's the right way to do it.
SwiftUI and undo
Undo and redo operations are implemented in SwiftUI TextEditors and TextFields by default.
If you want to manage these actions:
See UndoManager https://developer.apple.com/documentation/foundation/undomanager
For your multi-platform app, SwiftUI has an environment value for that: .undoManager. https://developer.apple.com/documentation/swiftui/environmentvalues/undomanager
Here's an example of .undoManager used to disable Undo.
struct ContentView: View {
@Environment(\.undoManager) var undoManager: UndoManager?
var body: some View {
VStack {
TextEditor(text: $text)
}
.task {
undoManager?.disableUndoRegistration()
}
}
}
If you still have questions, feel free to provide more information here.
Travis
Thanks for your answer, but I some problems:
-
When I edit TextField 1 and then select TextField 2, undo on TextField 1 doesn't work.
-
Undo after some editing sometimes throws an exception or crashes.
-
Selecting a TextField registers an undo.
and questions:
-
Where should I implement undo with a Toggle, Picker or List (move, delete)?
-
Is it possible to disable the built-in TextField undo and implement my own?