Custom Delete UITableViewCell

Discussion in 'iOS Programming' started by mdhansen5, Jun 1, 2012.

  1. mdhansen5 macrumors member

    Joined:
    Nov 22, 2010
    Location:
    Colorado
    #1
    I'd like to be able to use a custom button on my custom UITableViewCell to delete the cell, not the standard swipe-to-delete. I already have the button on the cell, so I don't need help with that. I do need help with creating the action to delete the cell.

    I've taken the code from editingStyle forRowAtIndexPath and put it into an IBAction but it doesn't work.

    Code:
    -(IBAction)deleteItem:(id)sender {
        
        [self.tableView beginUpdates];
        
        // Delete the item 
        Item *itemToDelete = [self.fetchedResultsController objectAtIndexPath:indexPath];
        NSLog(@"Deleting (%@)", itemToDelete.name);
        [self.managedObjectContext deleteObject:itemToDelete];
        [self.managedObjectContext save:nil];
        
        // Delete the row 
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
        [self performFetch];
        
        [self.tableView endUpdates];
    
    }
    I get 2 "use of undeclared identifier indexPath" errors. Does anyone have any idea how to accomplish this? Thanks a bunch to anyone that can help out.

    If it makes a difference, I'm using Core Data and NSFetchedResultsController
     
  2. ppilone macrumors 6502

    Joined:
    Jan 20, 2008
    #2
    The action isn't being triggered because you're most likely not setting it up when you initialize the cell. You'll need to connect your button's touch up inside event to your action in your tableView:cellForRowAtIndexPath: method (when you first initialize the cell).

    When your action is triggered, all you have is the button. You'll need to figure out how to go from that button to the index path of the table view row. There are a few options here:

    1. If your table view is simple enough you could set the tag of the button when you configure the cell and use that in your action to get your index path.
    2. Use UIView's methods to get the location of the button relative to your table and from there ask the table for the cell/index path.

    ... there may be other solutions to getting the index path but these were the first two I thought of...

    Just as a side note: there may be a legitimate reason why you need to support a custom delete button in a table view cell but you really need to think why you can't use the standard table view editing support. Will it be confusing to users to see a delete button in a row that differs from the standard editing actions?
     

Share This Page