devmiles.com
devmiles.com

Reputation: 10014

Can't change separator (custom UIView) color upon selection in UITableView

I'm changing cell color upon click and I'm also changing the little custom separator at the bottom of the cell. However when I call deselectRowAtIndexPath the separator color is restored to the color it had before ignoring my change. Why is this happening, how do I accomplish this simple task? Here's my code:

[tableView deselectRowAtIndexPath:indexPath animated:NO];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UIView *separator = [cell viewWithTag:SEPARATOR];
separator.backgroundColor = _colorOrangeSelected;

Upvotes: 0

Views: 340

Answers (3)

devmiles.com
devmiles.com

Reputation: 10014

I've solved the issue by subclassing UITableViewCell for my cells and overriding setSelected and setHighlighted methods. I guess native implementations just mess around with subviews and their backgrounds in a strange way that ignores their latest state.

Upvotes: 1

simalone
simalone

Reputation: 2768

UIView can not have a highlightedColor. You can try following solution: 1. Using UIButton or UIImageView which can set highlightedColor or highlightedImage 2. Using drawRect:

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    if (self.cellDevideLineColor != nil) {
        CGContextRef context = UIGraphicsGetCurrentContext();

        [self.cellDevideLineColor set];
        CGContextSetLineWidth(context, kCellLineHeight);

        CGContextMoveToPoint(context, 0, rect.size.height);
        CGContextAddLineToPoint(context, self.width, rect.size.height);
        CGContextStrokePath(context);
    }
}

Upvotes: 1

johnMa
johnMa

Reputation: 3311

Here is a solution:

  • drag a UIImageView to your cell and make it the separator. set the image and HightLightImage with two different image.

When selected cell, your custom cell will refresh subviews state automatically,but you have to prepare two images.

Upvotes: 1

Related Questions