Can't change image in selected custom cell

99封情书 提交于 2019-12-11 06:33:29

问题


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?


回答1:


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



回答2:


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

}




回答3:


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



来源:https://stackoverflow.com/questions/13844724/cant-change-image-in-selected-custom-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!