Changing background color of selected cell?

2019-01-07 07:23发布

Does anyone know how to change the background color of a cell using UITableViewCell, for each selected cell? I created this UITableViewCell inside the code for TableView.

24条回答
啃猪蹄的小仙女
2楼-- · 2019-01-07 08:08
- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    cell.contentView.backgroundColor = [UIColor yellowColor];
}

- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    cell.contentView.backgroundColor = nil;
}
查看更多
疯言疯语
3楼-- · 2019-01-07 08:09

If you just want to remove the grey background color do this :

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     [[tableView cellForRowAtIndexPath:indexPath] setSelectionStyle:UITableViewCellSelectionStyleNone];
}     
查看更多
叛逆
4楼-- · 2019-01-07 08:09

I was able to solve this problem by creating a subclass of UITableViewCell and implementing the setSelected:animated: method

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
    if(selected) {
        [self setSelectionStyle:UITableViewCellSelectionStyleNone];
        [self setBackgroundColor:[UIColor greenColor]];
    } else {
        [self setBackgroundColor:[UIColor whiteColor]];
    }
}

The trick was setting the

cell.selectionStyle = UITableViewCellSelectionStyleDefault;

in the implementing view controller and then in the tableViewCell setting it as

[self setSelectionStyle:UITableViewCellSelectionStyleNone];

Hope this helps. :)

查看更多
Anthone
5楼-- · 2019-01-07 08:10

If you're talking about selected cells, the property is -selectedBackgroundView. This will be shown when the user selects your cell.

查看更多
你好瞎i
6楼-- · 2019-01-07 08:13

I created UIView and set the property of cell selectedBackgroundView:

UIView *v = [[UIView alloc] init];
v.backgroundColor = [UIColor redColor];
cell.selectedBackgroundView = v;
查看更多
贪生不怕死
7楼-- · 2019-01-07 08:13

In Swift

let v = UIView()
    v.backgroundColor = self.darkerColor(color)
    cell?.selectedBackgroundView = v;

...

func darkerColor( color: UIColor) -> UIColor {
    var h = CGFloat(0)
    var s = CGFloat(0)
    var b = CGFloat(0)
    var a = CGFloat(0)
    let hueObtained = color.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
    if hueObtained {
        return UIColor(hue: h, saturation: s, brightness: b * 0.75, alpha: a)
    }
    return color
}
查看更多
登录 后发表回答