繁体   English   中英

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

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

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

视图控制器.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];
    
}

暂无
暂无

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

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