This tutorial picks up where our last tutorial on TableView Basics left off. Now that we have one, it’s time to start editing, deleting and moving things around. Again, we’ll have our starter project and our completed project downloads. For additional reading, you can check out the Apple guides on this.
First off, we can lose the button off the cell. Go to the storyboard and delete it. Move our label to the right a little bit, because we will need room for editing buttons later. Delete the button code we had in the delegate method in RootViewController.m:
To do editing, you place the table view in editing mode, which is done through another UITableView delegate method:
Run the project, and select any row. You should see delete buttons for each row. We can try to delete all we want, but nothing will happen until we use another delegate method
The default editing style of any cell is deleting, so we’ll start with that. Let’s add a new UITableView delegate method.
There are three important steps, identify the edit type, update the datasource array, then update the table view. Run the project, and delete away!
Inserting is just doing the opposite, and of course, we need another delegate method. Alter RootViewController.m to the following:
Run the project and start adding. Real world projects typical use an add button and some kind of modal to add whatever you want to add to the data. Usually it’s a simple append, or it may get resorted. The best use of UITableViewCellEditingStyleInsert is if you want to insert data in between two particular rows. The point here is just to show the insert edit mode in action. To change it back to delete, simply comment out the entire
Another typical editing type is moving data around the list to reorder the items. To enable moving, we’ll add two more UITableView delegate methods. Here’s the code:
First, we end up in edit mode by selecting the cell. The default for moving is NO, so we want to return YES instead. The moving of the items in the table view will happen on its own. However, we must update our datasource to show the reorder.
Notice we get a copy of the data in our array being moved, delete the object from the array, and insert the copy back into the array. Again we take ourselves out of editing mode at the end of the move. It is common to instead just stay in an edit mode and do many steps and have a “Done” button to stop editing. This method usually has a table view reload. It’s your choice. In our example, if you want to see the data changes, simply put a breakpoint in the
moveRowAtIndexPath method and observe the array.
Run the project. Once a cell is selected, the cell will show the drag handle on the far right of the cell. Hold this handle, and in a moment it will pop up slightly.
In order to edit a table view, simply put the table in editing mode. Then use the appropriate combination or UITableView delegate methods to control the editing.