Search code examples
iosuiimagetableviewcustom-cell

Can't change image in selected custom cell


I created a custom cell to display a text and 2 images, when the user selects the cell, the image is supposed to change. I can access the properties of the cell, but can't change them :

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    CustomCell *cell = (CustomCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    cell.check.image = setImage:[UIImage imageNamed:@"1355327732_checkbox-checked"];
    [cell.check setImage:[UIImage imageNamed:@"1355327732_checkbox-checked"]]; }

cell.check is a UIImageView

Am i missing something?


Solution

  • If you are using a custom cell then you can override the function setSelected:animated: like so...

    - (void)setSelected:(BOOL)selected animated:(BOOL)animated
    {
        [super setSelected:selected animated:animated];
    
        // Configure the view for the selected state
        if (selected) {
            self.check.image = [UIImage imageNamed:@"1355327732_checkbox-checked"];
        } else {
            self.check.image = nil;
        }
    }
    

    Then you don't have to do anything in the tableView code to change this. It will just work.

    A better alternative to this is to keep the image the same inside self.check. Then you can just set hidden to YES or NO accordingly. This will be more performant also.

    To have this so that you get multiple selections from the table then in the TableViewController put...

    self.tableView.allowsMultipleSelection = YES;
    

    This will set it so that you can select multiple rows. One tap selects and another tap deselects.

    To get the selected rows you can run...

    NSArray *selectedRows = [self.tableView indexPathsForSelectedRows];