Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable swipe to delete cell in a TableView?

I have a UIViewController that implements TableViews delegate and datasource protocols. Now I want to add "swipe to delete" gesture to cells.

How should I go about it.

I have given a blank implementation of commitEditingStyle method and also set the Editing property to YES.

Still the swipe feature is not coming .

Now Do I need to separately add UISwipeGesture to each cell ?

Or am I missing something ?

like image 371
Amogh Talpallikar Avatar asked Jan 24 '12 06:01

Amogh Talpallikar


People also ask

How do you clear a tableView cell?

So, to remove a cell from a table view you first remove it from your data source, then you call deleteRows(at:) on your table view, providing it with an array of index paths that should be zapped. You can create index paths yourself, you just need a section and row number.

How do you delete a row in tableView?

When a user slides horizontally across a row the editing style of the Tabel View Cell is set to delete. When the delete button is pressed, the item is deleted in the array and also the row is deleted in the Table View. Build and run the project and swipe-to-delete a row from the Table View.


2 Answers

As Dan has commented above, you need to implement the following table view delegate methods:

  1. tableView:canEditRowAtIndexPath:
  2. tableView:commitEditingStyle:forRowAtIndexPath:

Note: I have tried this in iOS 6 and iOS 7.

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {     // Return YES - we will be able to delete all rows     return YES; }  - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {     // Perform the real delete action here. Note: you may need to check editing style     //   if you do not perform delete only.     NSLog(@"Deleted row."); } 
like image 116
Dj S Avatar answered Sep 20 '22 11:09

Dj S


You don't have to set editing:YES if you need to show Delete button on cell swipe. You have to implement tableView:canEditRowAtIndexPath: and return YES from there for rows you need to edit/delete. This is not necessary when your tableView's dataSource is a subclass of UITableViewContoller - this method, if not overridden, returns YES by default. In all other cases you have to implement it.

EDIT: Together we have found the problem - tableView:editingStyleForRowAtIndexPath: returned UITableViewCellEditingStyleNone if table wasn't in editing mode.

like image 23
Kyr Dunenkoff Avatar answered Sep 20 '22 11:09

Kyr Dunenkoff