Chapter 25. Undo

The ability to undo the most recent action is familiar from macOS. The idea is that, provided the user realizes soon enough that a mistake has been made, that mistake can be reversed. Typically, a Mac application will maintain an internal stack of undoable actions; choosing Edit → Undo or pressing Command-Z will reverse the action at the top of the stack, and will also make that action available for redo.

Some iOS apps may benefit from an undo facility. Certain built-in views — in particular, those that involve text entry, namely UITextField and UITextView (Chapter 10) — implement undo already. And you can add it in other areas of your app.

Undo is provided through an instance of UndoManager, which basically just maintains a stack of undoable actions, along with a secondary stack of redoable actions. The goal in general is to work with the UndoManager so as to handle both undo and redo in the standard manner: when the user chooses to undo the most recent action, the action at the top of the undo stack is popped off and reversed and is pushed onto the top of the redo stack.

In this chapter, I’ll illustrate an UndoManager for a simple app that has just one kind of undoable action. More complicated apps, obviously, will be more complicated; on the other hand, iOS apps, unlike macOS apps, do not generally need deep or pervasive undo functionality. For more about the UndoManager class and how to use it, read Apple’s Undo Architecture and the class documentation.

Get Programming iOS 11 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.