Enabling Edit Mode in a View Controller

You can use the same view controller both to display and to edit content. When the editing mode is toggled, your custom view controller performs the necessary work to transition its view from a display mode to an editing mode (or vice versa).

Toggling Between Display and Edit Mode

To allow a custom view controller class to be used to both display and edit content, override the setEditing:animated: method. When called, your implementation of this method should add, hide, and adjust the view controller’s views to match the specified mode. For example, you might want to change the content or appearance of views to convey that the view is now editable. If your view controller manages a table, you can also call the table’s own setEditing:animated: method in order to put the table into the appropriate mode.

Figure 12-1 shows a view from the Contacts app that supports in-place editing. Tapping the Edit button in the upper-right corner tells the view controller to update itself for editing; the Done button returns the user to display mode. In addition to modifying the table, the view also changes the content of the image view and the view displaying the user’s name. It also configures the assorted views and cells so that tapping them edits their contents instead of performing other actions.

Figure 12-1  Display and edit modes of a view

The implementation of your own setEditing:animated: method is relatively straightforward—you check to see which mode your view controller is entering and adjust the contents of your view accordingly.

- (void)setEditing:(BOOL)flag animated:(BOOL)animated
{
    [super setEditing:flag animated:animated];
    if (flag == YES){
        // Change views to edit mode.
    }
    else {
        // Save the changes if needed and change the views to noneditable.
    }
}

Presenting Editing Options to the User

A common place in which to use an editable view is in a navigation interface. When implementing your navigation interface, you can include a special Edit button in the navigation bar when your editable view controller is visible. (You can get this button by calling the editButtonItem method of your view controller.) When tapped, this button automatically toggles between an Edit and Done button and calls your view controller’s setEditing:animated: method with appropriate values. You can also call this method from your own code (or modify the value of your view controller’s editing property) to toggle between modes.

For more information about adding an Edit button to a navigation bar, see View Controller Catalog for iOS.