TigerCoding
TigerCoding

Reputation: 8720

UITableView willSelectRowAtIndexPath fails to change image in cell

I have a programatically created table view that loads a cell from a nib

In cellForRowAtIndexPath, I manage cell UIImageView’s like this:

UIImageView *rowImageView = (UIImageView*) [cell.contentView viewWithTag:49];
[rowImageView [self imageForRow:row selected:NO]];

The normal image is displayed properly in the cell.

In order to change the cell image when selected, I use this method:

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];
    UITableViewCell* cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    UIImageView *rowImageView = (UIImageView*) [cell.contentView viewWithTag:49];
    [rowImageView setImage:[self imageForRow:row selected:YES]];

    // test
    // the view controller background is successfully changed to the selected image
    self.backgroundImageView.image = [self imageForRow:row selected:YES];
    // the row image view is not nil
    if( rowImageView == nil ) NSLog(@"nil");

    return indexPath;
}

I also ensured the table view allows selection, and tested selection by not setting the initial image view, tapping the cell and watching the default background color change to blue. So I know the selection is occurring, but for some reason the image isn’t changing.

Upvotes: 0

Views: 2094

Answers (2)

rmaddy
rmaddy

Reputation: 318774

Two problems:

1) In your willSelectRow... method, change:

UITableViewCell* cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];

to:

UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];

The way you are doing it you end up creating a new cell and updating its image. But that's not the cell that is being displayed.

2) In your cellForRow... method, you need to keep track of whether the cell should show the selected or unselected image and setup the cell with the proper image.

Upvotes: 4

Hossam Ghareeb
Hossam Ghareeb

Reputation: 7113

I faced this problem and used some thing like this in initWithCoder in MyCustomCell:

-(id)initWithCoder:(NSCoder *)aDecoder
{
  if (self  = [super initWithCoder:aDecoder]) {
    UIImageView *bgView = [[UIImageView alloc]initWithFrame:self.frame];
    bgView.backgroundColor = [UIColor colorWithRed:22.0 / 255.0 green:163.0 / 255.0 blue:171.0 / 255.0 alpha:1];
    self.selectedBackgroundView = bgView;
 }

  return self;
}

Gave it a try, it may help you

Upvotes: 0

Related Questions