Search code examples
iosobjective-cuitableviewcell

ios Get table view cell index when edit action is pressed


I have a table view that has cells with edit actions. When the user swipes one of the cells to the left, you can see the edit action buttons.

enter image description here

When the user taps one of the buttons, I need to get the index path of the cell that the buttons were clicked from. How can I do that?

NOTE, the edit action buttons arn't UIButtons, they are made like this.

-(NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
     UITableViewRowAction *button = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"Reply" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath)
                                    {

 nil;

                                    }];

    button.backgroundColor = [UIColor colorWithRed:0.1 green:0.4 blue:0.9 

    alpha:1.0]; //arbitrary color
    }

Solution

  • you need to override delegate method, which will get when you swipe row for edit/delete options.

    - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    
            NSLog(@"canEditRowAtIndexPath get called");
            NSLog(@"Index is %ld",indexPath.row);
            return YES;
    }
    
    - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            //delete object here
            NSLog(@"Index is %ld",indexPath.row);
            [tableView reloadData]; // tell table to refresh now
       }
    }
    
    - (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
    
        NSLog(@"accessoryButtonTappedForRowWithIndexPath method get called");
        NSLog(@"Index is %ld",indexPath.row);
    }