Search code examples
core-dataswiftuicloudkit

Enable Undo CoreData SwiftUI


Does anyone know how to have the Undo command in the menu bar enable when CoreData UndoManager has items to undo?

Here’s what I’ve done:

  • At app init I’m setting the Core Data PersistanceController UndoManager()

    persistenceController.container.viewContext.undoManager = UndoManager()

  • I can confirm the CoreData undoManager is set because I can programmatically call undo and it works (for instance after deletion)

  • HOWEVER the Undo command in the menuBar remains disabled.

As a side-note, the Undo command in the menuBar works correctly when I’m writing text in a TextField (it does automatically enable to undo text changes).

Huge thanks in advance, been trying things for a while and can’t find anything online


Solution

  • Context is not clear, but try (just an idea) to use Undo Manager from environment, like

    // ... somewhere in view where you change core data objects
    
    @Environment(\.managedObjectContext) var viewContext
    @Environment(\.undoManager) var undoManager
    
    // ...
    
    var body: some View {
      // ...
      .onAppear {
         viewContext.undoManager = undoManager
      }
    }