更改所选单元格的背景颜色?

问题描述 投票:49回答:24

有没有人知道如何使用UITableViewCell为每个选定的单元格更改单元格的背景颜色?我在TableView的代码中创建了这个UITableViewCell。

iphone uitableview colors background tableview
24个回答
90
投票

更改属性selectedBackgroundView是正确的,也是最简单的方法。我使用以下代码更改选择颜色:

// set selection color
UIView *myBackView = [[UIView alloc] initWithFrame:cell.frame];
myBackView.backgroundColor = [UIColor colorWithRed:1 green:1 blue:0.75 alpha:1];
cell.selectedBackgroundView = myBackView;
[myBackView release];

6
投票

对于iOS7 +,如果您使用的是Interface Builder,则将您的单元格子类化并实现:

Objective-C的

- (void)awakeFromNib {
    [super awakeFromNib];
    // Default Select background
    UIView *v = [[UIView alloc] init];
    v.backgroundColor = [UIColor redColor];
    self.selectedBackgroundView = v;
}

Swift 2.2

override func awakeFromNib() {
    super.awakeFromNib()
    // Default Select background
    self.selectedBackgroundView = { view in
        view.backgroundColor = .redColor()
        return view
    }(UIView())
}

5
投票

这与分组调用完美配合:实现UITableViewCell的自定义子类

这将尊重角落等......

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

    if(selected)
        [self setBackgroundColor:[UIColor colorWithRed:(245/255.0) green:(255/255.0) blue:(255/255.0) alpha:1]];
    else
        [self setBackgroundColor:[UIColor whiteColor]];

}

5
投票

如果您只想删除灰色背景颜色,请执行以下操作:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     [[tableView cellForRowAtIndexPath:indexPath] setSelectionStyle:UITableViewCellSelectionStyleNone];
}     

5
投票

我能够通过创建UITableViewCell的子类并实现setSelected:animated:方法来解决这个问题。

- (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]];
    }
}

诀窍是设置

cell.selectionStyle = UITableViewCellSelectionStyleDefault;

在实现视图控制器中然后在tableViewCell中将其设置为

[self setSelectionStyle:UITableViewCellSelectionStyleNone];

希望这可以帮助。 :)


4
投票

默认样式为灰色,如果以编程方式完成,则会破坏单元格的颜色。你可以这样做以避免这种情况。 (在斯威夫特) cell.selectionStyle = .None


3
投票

在斯威夫特

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
}

3
投票

查看AdvancedTableViewCellsApple's sample code

您将需要使用复合单元格模式。


3
投票

在Swift 3中,从照亮答案转换而来。

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    if(selected) {
        self.selectionStyle = .none
        self.backgroundColor = UIColor.green
    } else {
        self.backgroundColor = UIColor.blue
    }
}

(但只有通过释放手指确认选择后视图才会更改)


2
投票

创建自定义UITableViewCell。在您自定义类内部覆盖“setSelected”函数并更改contentView背景颜色。您也可以覆盖“setHighlighted”功能。

在Swift中:

class myTableViewCell: UITableViewCell {

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
        // Add your color here
        self.contentView.backgroundColor = UIColor.whiteColor()
    }

    override func setHighlighted(highlighted: Bool, animated: Bool) {
        // Add your color here
        self.contentView.backgroundColor = UIColor.whiteColor()
    }
}

2
投票

适合我

UIView *customColorView = [[UIView alloc] init];
    customColorView.backgroundColor = [UIColor colorWithRed:180/255.0 
                                                      green:138/255.0 
                                                       blue:171/255.0 
                                                      alpha:0.5];
    cell.selectedBackgroundView =  customColorView;

37
投票

我终于设法让这个工作在一个表格视图中,其样式设置为Grouped。

首先将所有细胞的selectionStyle属性设置为UITableViewCellSelectionStyleNone

cell.selectionStyle = UITableViewCellSelectionStyleNone;

然后在表视图委托中实现以下内容:

static NSColor *SelectedCellBGColor = ...;
static NSColor *NotSelectedCellBGColor = ...;

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSIndexPath *currentSelectedIndexPath = [tableView indexPathForSelectedRow];
    if (currentSelectedIndexPath != nil)
    {
        [[tableView cellForRowAtIndexPath:currentSelectedIndexPath] setBackgroundColor:NotSelectedCellBGColor];
    }

    return indexPath;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [[tableView cellForRowAtIndexPath:indexPath] setBackgroundColor:SelectedCellBGColor];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (cell.isSelected == YES)
    {
        [cell setBackgroundColor:SelectedCellBGColor];
    }
    else
    {
        [cell setBackgroundColor:NotSelectedCellBGColor];
    }
}

1
投票

以下是在Interface Builder(在Storyboard中)中执行此操作的快速方法。将一个简单的UIView拖到UITableView的顶部,如下一步将单元格的selectedBackgroundView Outlet连接到此视图。您甚至可以将多个单元的出口连接到这个视图。


1
投票

对于通过UIAppearance的子类化并使用其默认的UITableViewCell设置颜色(适用于)适用于iOS 7(及更高版本)的selectedBackgroundView的解决方案,请查看我对类似问题here的回答。


1
投票
- (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;
}

1
投票

我在上面的答案中尝试了每一个,但它们都不适合我,

然后我调查了一个本机提供的方法,它工作正常。

首先,将cellSelectionStyle设置为None,然后转到此解决方案。

func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath?
{   
    let cell = tableView.cellForRow(at: indexPath);

   //cell which is getting deselected, make whatever changes that are required to make it back normal        

    cell.backgroundColor = kNormalColor;

    return indexPath;
}

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath?
{
    let cell = tableView.cellForRow(at: indexPath);

   //cell which is getting selected, make whatever changes that are required to make it selected        

    cell.backgroundColor = kSelectedColor;

    return indexPath;
}

这种方法优于其他方法的优点是:

  1. 它适用于多个细胞选择
  2. 您可以根据需要更改任何元素,不仅可以更改给定单元格的背景颜色,也可以取消选择。

1
投票
override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    if selected {
        self.contentView.backgroundColor = .black
    } else {
        self.contentView.backgroundColor = .white
    }
}

19
投票
// animate between regular and selected state
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {

    [super setSelected:selected animated:animated];

    if (selected) {
        self.backgroundColor = [UIColor colorWithRed:234.0f/255 green:202.0f/255 blue:255.0f/255 alpha:1.0f];
    }
    else {
        self.backgroundColor = [UIColor clearColor];
    }
}

11
投票
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

     UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
     cell.contentView.backgroundColor = [UIColor yellowColor];

}

10
投票

SWIFT 4, XCODE 9, IOS 11

经过一些测试后,当表视图选择设置为“多选”时,将取消选择时删除背景颜色或再次点击单元格。当表格视图样式设置为“Grouped”时也可以使用。

extension ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let cell = tableView.cellForRow(at: indexPath) {
            cell.contentView.backgroundColor = UIColor.darkGray
        }
    }
}

注意:为了使其能够如下所示工作,您的单元格的Selection属性可以设置为任何但是无。

How it looks with different options

风格:平原,选择:单一选择

Single Selection

风格:平原,选择:多重选择

Multiple Selection

风格:分组,选择:多重选择

Grouped Multiple Selection

Bonus - Animation

要获得更平滑的颜色过渡,请尝试一些动画:

extension ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let cell = tableView.cellForRow(at: indexPath) {
            UIView.animate(withDuration: 0.3, animations: {
                cell.contentView.backgroundColor = UIColor.darkGray
            })
        }
    }
}

Animated color transition

Bonus - Text and Image Changing

您可能会注意到选择单元格时图标和文本颜色也会发生变化。当您设置UIImage和UILabel突出显示的属性时,会自动发生这种情况

的UIImage

  1. 提供两个彩色图像:

Two colored images

  1. 设置突出显示的图像属性:

Highlighted property

的UILabel

只需为突出显示的属性提供颜色:

Highlighted Color


9
投票

我创建了UIView并设置了cell selectedBackgroundView的属性:

UIView *v = [[UIView alloc] init];
v.backgroundColor = [UIColor redColor];
cell.selectedBackgroundView = v;

7
投票

如果您正在谈论选定的单元格,则该属性为-selectedBackgroundView。当用户选择您的单元格时,将显示此信息。


6
投票

我对以下内容感到满意:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    bool isSelected = // enter your own code here
    if (isSelected)
    {
        [cell setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:0.75 alpha:1]];
        [cell setAccessibilityTraits:UIAccessibilityTraitSelected];
    }
    else
    {
        [cell setBackgroundColor:[UIColor clearColor]];
        [cell setAccessibilityTraits:0];
    }
}

6
投票

我有一个高度定制的UITableViewCell。所以我实现了自己的细胞选择。

cell.selectionStyle = UITableViewCellSelectionStyleNone;

我在我的单元格类中创建了一个方法:

- (void)highlightCell:(BOOL)highlight
{
    if (highlight) {
        self.contentView.backgroundColor = RGB(0x355881);
        _bodyLabel.textColor = RGB(0xffffff);
        _fromLabel.textColor = RGB(0xffffff);
        _subjectLabel.textColor = RGB(0xffffff);
        _dateLabel.textColor = RGB(0xffffff);
    }
    else {
        self.contentView.backgroundColor = RGB(0xf7f7f7);;
        _bodyLabel.textColor = RGB(0xaaaaaa);
        _fromLabel.textColor = [UIColor blackColor];
        _subjectLabel.textColor = [UIColor blackColor];
        _dateLabel.textColor = RGB(0x496487);
    }
}

在ViewWillAppear的UITableViewController类中添加了以下内容:

NSIndexPath *tableSelection = [self.tableView indexPathForSelectedRow];
SideSwipeTableViewCell *cell = (SideSwipeTableViewCell*)[self.tableView cellForRowAtIndexPath:tableSelection];
[cell highlightCell:NO];

在didSelectRow中添加了这个:

SideSwipeTableViewCell *cell = (SideSwipeTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];
[cell highlightCell:YES];
© www.soinside.com 2019 - 2024. All rights reserved.