« Dismissing the iPhone Keyboard | Main | Xcode Tip: Column mode text Selecting »
Monday
Sep282009

iPhone TableView: Swiping a cell to delete

One of the elegant features added to the iPhone mail app was the ability to swipe your finger from left to right on a tableView cell and have the delete button appear (like the right image below) to delete an item from the tableView.

 

Many people have asked me if this is possible to do for their own iPhone app.tableviewdelete 

The short answer is Yes but you have to use a couple of undocumented API calls. It's actually quiet easy. Set the cell's editingStyle to UITableViewCellEditingStyleDelete. This is an undocumented feature. Currently the documentation will show that it's a read only property. However there is nothing stopping one from setting the set property. A compiler warning like below will appear when implementing the set property.

 

 

Editing Style Warning for setting the style

To set the style, do it either in the cellForRowAtIndexPath method or implement a TableViewCell object. I'm not going to get into details of how to create a cell, I assume you already know how to do that.

- (UITableViewCell *)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
   // Add your code here to create the cell
    .....
    [cell setEditingStyle:UITableViewCellEditingStyleDelete];
}

The final set step is to actually do something when the user swipes the cell and clicks the Delete button. This is handled by adding the commitEditingStyle message to the view.

- (void)tableView:(UITableView*)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)
{
    if (editingStyle == UITableViewCellEditingStyleDelete)    {
        //Add Code to delete from the Data Source
    }
}

That's all to it. A very simple implementation for an elegant solution. I'm still miffed why this is undocumented, so be warned, you could have Apple decline your app because of the usage of an undocumented feature. UPDATE: iPhone 3.0 SDK you no longer have to set the EditingStyle of the Cell.

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>