SwiftUI and undo

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.

Answered by DTS Engineer in 878693022

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

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

SwiftUI and undo
 
 
Q