Search code examples
iphoneuitableviewdidselectrowatindexpath

Turning a cell in a UITableView on/off on the same cell, in the same view


Is it possible to make one cell in a UITableView have an ON/OFF behavior? Basically, when I click a cell, it becomes green, which is what I want. It doesnt go to another viewController or anything. But then when I click that same cell again, in the same view, I want the green to disappear and for it to return back to it's previous color state.

This is how I have my didSelectRowAtIndexPath

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *selectedPhrase = [dataTable objectAtIndex:indexPath.row];
    [self setCurrentPhrase:selectedPhrase];
}

This seems like an easy question. I know I can drop in the [tableView deselectRowAtIndexPath:indexPath animated:YES]; but that just makes it unhighlighted right away after I click it.

Thanks!

Aaron


Solution

  • you could change the background color of you UITableViewCell on selection, So you may use BOOL which will tell you what to fill in background (whether green or just clear color).

    Access you cell through the below method

    - (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath
    

    Use below as the reference code.

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        NSString *selectedPhrase = [dataTable objectAtIndex:indexPath.row];
        [self setCurrentPhrase:selectedPhrase];
    
          MyCutsomCell* myCell= (MyCutsomCell*)[tableView cellForRowAtIndexPath:indexPath];
          if(myCell.isGreen)
          {
             //Change backgroundColor to Green
          }
          else
          {
             //Clear backgroundColor
          }
    
          myCell.isGreen = !myCell.isGreen;
    }