UndoManager Tutorial: How to Implement With Swift Value Types

In this tutorial you’ll learn how to build an undo manager, using Swift and value types, leveraging the Foundation’s UndoManager class By Lyndsey Scott.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

Undoing People List Changes

At the end of peopleModelDidChange(diff:), add:

// 1
undoManager.registerUndo(withTarget: self) { target in
  // 2
  target.modifyModel { model in
    model = diff.from
  }
}
// 3
DispatchQueue.main.async {
  self.undoButton.isEnabled = self.undoManager.canUndo
  self.redoButton.isEnabled = self.undoManager.canRedo
}

Here, you:

  1. Register an undo operation capable of undoing data model and UI changes.
  2. Modify the people model by replacing the current model with the previous one.
  3. Enable/disable undoButton and redoButton appropriately.

In undoTapped(), add:

undoManager.undo()

and in redoTapped(), add:

undoManager.redo()

to trigger undo and redo respectively.

Last but not least, add shake to undo/redo to this controller. At the end of viewDidAppear(_:), add:

becomeFirstResponder()

At the end of viewWillDisappear(_:), add:

resignFirstResponder()

And beneath viewWillDisappear(_:), add:

override var canBecomeFirstResponder: Bool {
  return true
}

so that the controller can undo/redo in response to the shake gesture.

That's it! Build and run. You can edit, add, undo, redo, shake, etc.

You did it!

Where to Go From Here?

Download the final project using the Download Materials link at the bottom or top of this tutorial to see how it compares to your version.

To further explore the UndoManager API, try grouping undo features, naming undo actions, making undo operations discardable and using the various built-in notifications.

To further explore value types, try adding properties to Person and PeopleModel to make your app more robust.

And if you want to make your PeopleKeeper really work for you, add data persistence between app launches. See our "Updated Course: Saving Data in iOS" for more information.

Have any questions, comments or suggestions? Join in the forum discussion below!