简体   繁体   中英

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;

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.

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);
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM