Swiping-to-Delete Table Rows

Swipe-to-delete is a signature iOS interaction. Notably available in Mailapp, deleting and editing data in UITableViews is a built-in API and an easy way to add some polish to your app.

To allow the user to delete table rows, you need to implement yet more dataSource methods.

  • tableView:editingStyleForRowAtIndexPath:, where we determine how each row can be edited. If a row can be edited, then the table view will change the UI accordingly. After the user has acted upon that UI, like tapping the Delete button, we call commitEditingStyle:forRowAtIndexPath:.

  • tableView:commitEditingStyle:forRowAtIndexPath:, which is called after the user has edited or deleted some table view element. At this point, we need to actually alter our original data structure to reflect those changes.

In our case, editingStyleForRowAtIndexPath: can be implemented pretty quickly. In practice, you may want some rows to be uneditable by using indexPath-based logic, but we’re going to let every row in this app be deletable.

 def​ tableView(tableView, ​editingStyleForRowAtIndexPath: ​indexPath)
  UITableViewCellEditingStyleDelete
 end

commitEditingStyle:forRowAtIndexPath: isn’t so bad either. Just use the Array delete_at method to mutate our @data and then use UITableView’s reloadData to refresh our view.

 def​ tableView(tableView,
  commitEditingStyle​:editingStyle​, forRowAtIndexPath​:indexPath​)
 if​ editingStyle == UITableViewCellEditingStyleDelete
  rows_for_section(indexPath.section).delete_at indexPath.row
  tableView.reloadData
 end
 end

Let’s give it a whirl, preferably with rake device because it’s tricky to trigger with the simulator. It works, but it’s kind of jarring how the row suddenly pops out of sight. Luckily, as with many things in iOS, we can animate it!

images/tables/table_delete.png

Animating Table Views

UITableView has some prepackaged methods for animating changes to its contents. In place of reloadData in commitEditingStyle:, we’ll use deleteRowsAtIndexPaths:withRowAnimation:. This will automatically reload the table’s data after the animation, so we don’t need to worry about refreshing it ourselves. However, it means that the changes to the data source correspond precisely to animated changes, so don’t try to animate removing five rows when you removed only four from your data.

 if​ editingStyle == UITableViewCellEditingStyleDelete
  rows_for_section(indexPath.section).delete_at indexPath.row
» tableView.deleteRowsAtIndexPaths([indexPath],
» withRowAnimation​:UITableViewRowAnimationFade​)
 end

All we need is a one-line change to really make the app look slick. There are other UITableViewRowAnimations like UITableViewRowAnimationRight or UITableViewRowAnimationBottom; always play around and choose one appropriate for your design.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset