Search code examples
iphoneiosipad

How to deselect a selected row when selecting the new row in a tableview?


I have an application in which i need to deselect the selected cell when the user selecting a new cell. I can do the selecting and deselecting the tableview rows, but the problem is I need to select only one row at a time. I was doing like this now,

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
   cell.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"white_cell_check.png"]];   

}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
      UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

     cell.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"white_cell.png"]]; 

}

but in this i can select and deselect the same row. But my intention is when selecting a new row if any other cells are selected already it needs to deselected. Can any body help me ?


Solution

  • A naive solution would be

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
      for (int i = 0; i < [tableView numberOfRowsInSection:0]; i++) {
          [tableView deselectRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
      } 
       UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
       cell.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"white_cell_check.png"]];   
    
    }
    
    - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
    {
          UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
         cell.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"white_cell.png"]]; 
    
    }
    

    Basically you are looping through all cells deselecting them whenever you select a new one.