How to toggle UITableView Cell selected status

ios, ios5, ios6, uitableview

Solution

you have to save the index path of the selected row in didSelectRowAtIndexPath and check the index path in cellForRowAtIndexPath: set the corresponding image

Do you want multiple selection? try this...

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell * cell = (CustomCell* )[tableView cellForRowAtIndexPath:indexPath];

if(indexPath.row == 0)
{
    if(cell.selectionStatus == YES)
    {     
      [self.checkedIndexPaths addObject:indexPath];
        //Do your stuff
       cell.selectionStatus = NO;
    }
    else
    {
        [self.checkedIndexPaths removeObject:indexPath];
        //Do your stuff
        cell.selectionStatus = YES;
    }
}
}  

Edit In cellForIndexPath check like this

 // Set the default image for the cell. imageXYZ   
for (NSIndexPath *path in self.checkedIndexPath) 
{
    if ([path  isEqual:indexPath])
    {
        //set the changed image for the cell. imageABC
    }
    // no need of else part
}

Do the exact we will see

Problem

I have a UITableView with a custom Cell, the cell contains a UIImageView and a UILabel. Now When I load my table first time, It loads with a same image on each cell and different labels, which it takes from the LabelArray. Now the image I am talking about is a radioButton, So when the user clicks the cell, the image changes. If user clicks again it changes to default state. For this to happen, I have used this function and also I have declared a bool variable in my customcell class called selectionStatus. ``` - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { CustomCell * cell = (CustomCell* )[tableView cellForRowAtIndexPath:indexPath]; if(indexPath.row == 0) { if(cell.selectionStatus == TRUE) { //Do your stuff cell.selectionStatus = FALSE; } else { //Do your stuff cell.selectionStatus = TRUE; } } if(indexPath.row == 1) { if(cell.selectionStatus == TRUE) { //Do your stuff cell.selectionStatus = FALSE; } else { //Do your stuff cell.selectionStatus = TRUE; } } } ``` This works fine, (but I want to know whether it is a proper way, or can we check the cell.selected property) and I am able to get that effect. But now when I close the View and open it again the function Edit based on below comments with @Anil ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { if([self.checkedIndexpath count] == 0) { [tableCell.selectionImage setImage:@"xyz.png"]; } else { for (int i =0; i <[self.checkedIndexPath count]; i++) { NSIndexPath *path = [self.checkedIndexPath objectAtIndex:i]; if ([path isEqual:indexPath]) { [tableCell.selectionImage setImage:@"abc.png"] } else { [tableCell.selectionImage setImage:@"xyz.png"] } } return tableCell; ``` Regards Ranjit

Original source