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.
Two problems:
1) In your
willSelectRow...
method, change:to:
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.