JAA
JAA

Reputation: 1024

Add "Swipe to delete" but not in all cells

I want to add in my tableview the possibility to "swipe to delete", but I don't want this for the last cell of the table!

I can check in - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath if the indexPath.row is the last one, but what I want is that if the user swipes on the last cell, nothing will appear (while in the others cells appears the text "delete").

I've tried this

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.row != ([array count]-1)) {
   return @"delete";
 }
 else {
     NSString *a;
     return a;
  }
}

but of course it doesn't works (the app crashes). I've tried with

return @"";

but the red button appears (with no text)!

What do you suggest me? Thanks!

Upvotes: 1

Views: 265

Answers (2)

DarkDust
DarkDust

Reputation: 92335

The app crashes since you return an uninitialized pointer. But even then, you're doing it wrong ;-)

You want to implement tableView:editingStyleForRowAtIndexPath: and return UITableViewCellEditingStyleDelete for all cells, except for the last. You need to return UITableViewCellEditingStyleNone for the last cell to prevent that it can be deleted.

Upvotes: 3

Paul Warkentin
Paul Warkentin

Reputation: 3899

Try

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([indexPath row] == [tableView numberOfRowsInSection:[indexPath section]] - 1)
    {
        return UITableViewCellEditingStyleNone;
    }

    return UITableViewCellEditingStyleDelete;
}

Upvotes: 3

Related Questions