Claus
Claus

Reputation: 5722

UIImageView in UITableViewCell not getting highlighted when cell is selected

I have a UITableView where each cell contains an UIImageView of a product (loaded asynchronously but always with a solid white background) and a UILabel. When I click on it the selected cell gets highlighted but not the UIImageView. I knew there was this property

imageView.highlightedImage = [UIImage imagedNamed:@"product_highlighted"];

but it's clear this works only with static images while, in this case, I'm working with a dynamic one so I don't have the image till it gets loaded.

How can I fix this problem?

Upvotes: 0

Views: 861

Answers (2)

Claus
Claus

Reputation: 5722

This is the solution I came up with. It works if the background of the image is white. I've added to the TableviewDidSelectRow method

- (UIImage*) addLayerTo:(UIImage*)source withAlpha:(double)alpha
{
    CGSize size = [source size];
    UIGraphicsBeginImageContext(size);
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    [source drawInRect:rect blendMode:kCGBlendModeNormal alpha:1.0];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, alpha);
    CGContextFillRect(context, rect);
    UIImage *testImg =  UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return testImg;
}

It basically adds a black layer with a specific alpha transparency which will merge seamlessly with the cell selected background. I took inspiration from this article

Upvotes: 0

Teo
Teo

Reputation: 3442

You should create your custom UITableViewCell subclass and override setHighlighted:animated:

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated
{
    [super setHighlighted:highlighted animated:animated];
    [imageView setHighlighted:highlighted];
}

From the Apple docs:

Note that for highlighting to work properly, you must fetch the cell’s label (or labels) using the textLabel (and detailTextLabel properties and set the label’s highlightedTextColor property; for images, get the cell’s image using the imageView property and set the UIImageView object’s highlightedImage property.

Upvotes: 2

Related Questions