darkman
darkman

Reputation: 1003

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?

Upvotes: 1

Views: 1687

Answers (3)

Midhun MP
Midhun MP

Reputation: 107121

I noticed two issues in your code

1) This code :

cell.check.image= setImage:[UIImage imageNamed:@"1355327732_checkbox-checked"];

2) There is no extension provided for the image

Replace it with:

cell.check.image= [UIImage imageNamed:@"1355327732_checkbox-checked.png"];

Upvotes: 0

Fogmeister
Fogmeister

Reputation: 77631

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];

Upvotes: 2

Mark McCorkle
Mark McCorkle

Reputation: 9414

Why are you calling setImage and cell.check.image on the same line? Try this and see if the result is the same.

- (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"]]; 

}

Upvotes: 0

Related Questions