繁体   English   中英

获取所选单元格的索引路径

[英]Get the indexpath of the selected cell

当用户在UITableView编辑模式下点击默认delete按钮时,用户应该获得一个警报视图,如果他在AlertView中再次点击删除,该行应该被删除。最初,我使用以下代码完成此操作而没有AlertView,它工作正常。

  [[self categoriesArray]removeObjectAtIndex:[indexPath row]];
   NSArray *indexPathsToRemove = [NSArray arrayWithObject:indexPath];
   [self.tableView deleteRowsAtIndexPaths:indexPathsToRemove withRowAnimation:UITableViewRowAnimationLeft];
   [self.categoriesArray writeToFile:[self dataFilePath]  atomically:YES];

但是现在,因为我必须在alertview委托方法中使用相同的代码。我不知道如何获取[indexPath row]

将索引路径设置为UIAlertView标记并从Delegate获取。

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath // indexPath is here
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
       UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Are you sure want to delete" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Delete", nil];
       [alertView setTag:indexPath.row]; // Assigning here.
        [alertView show];
    }
}
    // UIAlertView Delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"%d",alertView.tag); // Your Indexpath is here

**Edited:**

    NSIndexPath * path = [NSIndexPath indexPathForRow:alertView.tag inSection:0];
    [[self categoriesArray]removeObjectAtIndex:[path row]];
    NSArray * indexPathsToRemove = [NSArray arrayWithObject:path];
    [self.tableView deleteRowsAtIndexPaths:indexPathsToRemove withRowAnimation:UITableViewRowAnimationLeft];
    [self.categoriesArray writeToFile:[self dataFilePath]  atomically:YES];
}

将标记设置为commitEditingStyle方法的警报视图

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath // indexPath is here
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
       UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Delete Record" message:@"Are you sure to delete the record." delegate:self cancelButtonTitle:@"NO" otherButtonTitles:@"YES", nil];
       alert.tag = indexPath.row;
       [alert show];
    }
}

Alert delegate方法上

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
     if(buttonIndex == 1)//YES button clicked
     {
         [[self categoriesArray]removeObjectAtIndex:alertView.tag];
     }
}

UITableView通过以下方式为您提供此信息:

- (NSIndexPath *)indexPathForSelectedRow

或者如果做出多项选择:

- (NSArray *)indexPathsForSelectedRows

在此委托方法中使用警报视图

  - (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath

然后在用户单击“删除”时执行您想要执行的操作。 如果用户在alertview中预先删除,则必须使用alert view delegate方法来处理它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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