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:
- Register an undo operation capable of undoing data model and UI changes.
- Modify the people model by replacing the current model with the previous one.
- 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.
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!