簡體   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