Can TextField handle undo?

I'm struggling to understand whether TextField handles undo by itself, or how to properly handle it myself.

In a macOS app with a SwiftUI lifecycle, in a DocumentGroup scene, I'm using both TextEditors and Textfields. The text editors handle undo out of the box, with undo coalescing.

The text fields seem not to. However, on occasion, they do create undo points, leaving me confused as to what conditions are needed for that to happen.

Is there a way to reliably get text fields to handle undo on their own? Or, how should I implement typing undo, including undo coalescing, manually?

In MacOS with AppKit, you get it directly in the storyboard, by activating the undo checkbox.

Hope that helps.

Thanks for the tip! I am using SwiftUI, however, so its's the SwiftUI TextEditor and TextField views that I'm trying to understand.

Hello @Cykelero,

The undo is a system-level control. Since you are creating a Mac app, that control would be handled best by AppKit.

If @Claude31 suggestion does not work do you mind providing more info?

 Travis Trotto - DTS Engineer

To more clearly state my question, what I’m really asking is: how does SwiftUI’s TextField work with Undo? What are the conditions to making that work?

Hello @Cykelero,

On iPhone, users shake the phone to undo. This is a system setting.

From what I found and tried, I don't think TextField or even SwiftUI can disable that interaction on iPhone. But on Mac you can use the toggles listed above or the ⌘+Z function can be overwritten with AppKit commands

Let me get a confirmation that I'm not missing anything, if possible. In the meantime let me know if this helps.

 Travis Trotto - DTS Engineer

Sorry for not replying earlier. No, I'm afraid that info isn't what I'm looking for. The thing that I'd like to understand really is, specifically: how to use the built-in undo support of SwiftUI TextField views, if any.

Hopefully you're able to get details on this somehow!

I investigated further and found your answer!

UndoManager is the API in the Foundation framework for undo/redo and SwiftUI has an environment value for that undoManager.

This example disables undo on TextField on Mac

struct ContentView: View {

    @Environment(\.undoManager) var undoManager: UndoManager?

    var body: some View {
        VStack {
            TextField("Test", text: $text)
        }
        .task {
            undoManager?.disableUndoRegistration()
        }
    }
}

Let me know if this answers your question

 Travis Trotto - DTS Engineer

Thank you for your research. Your reply prompted me to try things differently, and turns out, the particular way we had text fields set up in our app was the reason their undo was flaky. Embarrassing, but at least all is clear now!

Can TextField handle undo?
 
 
Q