Obj-C - 在点击另一个单元格时取消选择选定的单元格?

Obj-C - Deselect the selected cell when another cell is tapped?

我目前正在为 didSelectRowAtIndexPath 使用以下代码。按照我现在编写代码的方式,如果用户点击一个单元格,则会出现一个绿色复选标记。如果他们再次点击同一个单元格,绿色复选标记就会消失。也就是说,我想这样做,如果用户在做出选择后点击不同的单元格,绿色复选标记应该从先前选择的单元格中消失。我怎样才能做到这一点?

ViewController.m

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
 
    if(_selectedRowIndex && indexPath.row == _selectedRowIndex.row) {

         ClientTableViewCell *cell2 = [tableView cellForRowAtIndexPath:indexPath];
         cell2.greenCheck.image = [UIImage imageNamed:@""];

        
          [tableView deselectRowAtIndexPath:indexPath animated:YES];
          _selectedRowIndex = nil;

      }

      else {  self.selectedRowIndex = indexPath;
          
        
          ClientTableViewCell *cell2 = [tableView cellForRowAtIndexPath:indexPath];
          
          NSDictionary *client =  self.sectionClients[indexPath.section][indexPath.row];
          
          cell2.greenCheck.image = [UIImage imageNamed:@"added.png"];
      
    NSLog(@"SELECTED");
          
          
      }

      [tableView beginUpdates];
      [tableView endUpdates];
    
}

You can store the last selected indexpath, when a new cell is selected, you get the previous cell with the stored indexpath and deselect it.

@implementation ViewController

NSIndexPath *lastIndexPath;
 
...

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
 
    if (lastIndexPath != nil){
        UITableViewCell *oldCell = [self.tableView cellForRowAtIndexPath:lastIndexPath];
        oldCell.accessoryType = UITableViewCellAccessoryNone;
    }

   
    if(lastIndexPath != indexPath) {
        lastIndexPath = indexPath;
        UITableViewCell *cell2 = [tableView cellForRowAtIndexPath:indexPath];
        cell2.accessoryType = UITableViewCellAccessoryCheckmark;
    }else{
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        lastIndexPath = nil;
    }
    [tableView beginUpdates];
    [tableView endUpdates];
    
}