2

当用户在编辑模式下点击默认delete按钮时UITableView,用户应该得到一个警报视图,如果他在 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]

4

4 回答 4

4

将您的 indexpath 设置为UIAlertViewTag 并从 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];
}
于 2013-04-05T12:50:39.400 回答
2

在 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];
     }
}
于 2013-04-05T12:49:26.973 回答
1

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

- (NSIndexPath *)indexPathForSelectedRow

或者如果进行了多项选择:

- (NSArray *)indexPathsForSelectedRows

于 2013-04-05T12:47:03.473 回答
1

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

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

然后在用户单击删除时执行您想做的任何事情。如果用户在警报视图中按下删除,那么您必须使用警报视图委托方法来处理它。

于 2013-04-05T12:47:45.487 回答