1

I made a UITableViewCell nib with a button on it. When the button is pressed, I want to delete the cell. The table view isn't in editing mode and I'm not using a standard UITableViewCell delete button.

I could store the row number in the button tag from cellForRowAtIndexPath, and use that to determine the row to delete, but when a cell is deleted, the button tags will be incorrect.

Any ideas how I can identify what button press relates to what row?

TigerCoding
  • 8,710
  • 10
  • 47
  • 72

3 Answers3

3

Like in this answer:

CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
Community
  • 1
  • 1
lootsch
  • 1,867
  • 13
  • 21
1

If your button is a subview of cell's content view (as it should be). You can get the index path for the cell with button like this:

UIView *cellContentView = yourButton.superview;
UITableViewCell *cell = cellContentView.superview;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];

Then, just delete the cell:

[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                 withRowAnimation:UITableViewRowAnimationAutomatic];
[tableView endUpdates];
Rafał Sroka
  • 39,540
  • 23
  • 113
  • 143
0

if the method the button calls has a signature like:

-(void)action:(id)sender;

sender will be the UIButton that called the action so:

UIButton *button = (UIButton *)sender;
UITableViewCell *cell = [[button superview] superview];

should get you what you want.

Murillo
  • 1,043
  • 8
  • 9