简体   繁体   中英

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.

在此处输入图片说明

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
    }

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);
}

first set

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{......
editbutton.tag=index.row
   [editbutton addTarget:self action:@selector(clickOn:) forControlEvents:UIControlEventTouchUpInside];

....
}

than in

-(IBAction)clickOn:(id)sender
{
    UIButton *btn=(UIButton *)sender;
    nslog(@"%d",btn.tag);


}

Try this

write this in your UITableViewCell

NSIndexPath *indexPath = [(UITableView *)self.superview indexPathForCell: self];

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM