选择时如何更改UITableViewCell的颜色?

时间:2013-04-28 17:30:16

标签: ios objective-c uitableview colors

我有一个这样的菜单:

Menu

每个单元格的正常(未选定)状态是图像,所选状态也是图像(看起来像默认的蓝色图像)。但是,我想添加一个额外的第三个图像,这样当用户选择一个单元格时,它会在变为蓝色(选中)之前短暂更改为第三个颜色。

这是我的代码:

(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView setBackgroundColor:[UIColor clearColor]];

    NSString *cellIdentifier = @"MenuItemCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle  reuseIdentifier:cellIdentifier];
    }

    UIImage *cellBackgroundNormal = [UIImage imageNamed:@"cell_menu_normal"];
    UIImage *cellBackgroundSelected = [UIImage imageNamed:@"cell_menu_selected"];
    UIImageView *cellBackgroundView = [[UIImageView alloc] initWithImage:cellBackgroundNormal];
    UIImageView *cellBackgroundSelectedView = [[UIImageView alloc] initWithImage:cellBackgroundSelected];
    cell.backgroundView = cellBackgroundView;
    cell.selectedBackgroundView = cellBackgroundSelectedView;

    [cell.textLabel setBackgroundColor:[UIColor clearColor]];
    [cell.textLabel setTextColor:[UIColor whiteColor]];
    [cell.textLabel setFont:[UIFont boldSystemFontOfSize:17.0]];
    cell.textLabel.text = [self.menuItems objectAtIndex:indexPath.row];

    return cell;
} 

如你所见,到目前为止我只有两种状态。我不知道如何为第三张图片引入某种cell.hoveredBackgroundView。如果有人可以帮我实现这一点,我真的很感激。

15 个答案:

答案 0 :(得分:92)

iOS 6.0及更高版本

- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}

- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
  // Add your Colour.
    CustomCell *cell = (CustomCell *)[tableView cellForRowAtIndexPath:indexPath];
    [self setCellColor:[UIColor whiteColor] ForCell:cell];  //highlight colour
}

- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath {
  // Reset Colour.
    CustomCell *cell = (CustomCell *)[tableView cellForRowAtIndexPath:indexPath];
    [self setCellColor:[UIColor colorWithWhite:0.961 alpha:1.000] ForCell:cell]; //normal color

}

- (void)setCellColor:(UIColor *)color ForCell:(UITableViewCell *)cell {
    cell.contentView.backgroundColor = color;
    cell.backgroundColor = color;
}

自定义UITableViewCell

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

    UIView * selectedBackgroundView = [[UIView alloc] init];
    [selectedBackgroundView setBackgroundColor:[UIColor colorFromHexString:@"5E6073"]]; // set color here
    [self setSelectedBackgroundView:selectedBackgroundView];
}

答案 1 :(得分:32)

使用Swift的iOS 8.0(及更高版本)

Swift 2

override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}

override func tableView(tableView: UITableView, didHighlightRowAtIndexPath indexPath: NSIndexPath) {
    var cell = tableView.cellForRowAtIndexPath(indexPath)
    cell?.contentView.backgroundColor = UIColor.orangeColor()
    cell?.backgroundColor = UIColor.orangeColor()
}

override func tableView(tableView: UITableView, didUnhighlightRowAtIndexPath indexPath: NSIndexPath) {
    var cell = tableView.cellForRowAtIndexPath(indexPath)
    cell?.contentView.backgroundColor = UIColor.blackColor()
    cell?.backgroundColor = UIColor.blackColor()
}

Swift 3

override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
    return true
}

override func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath)
    cell?.contentView.backgroundColor = UIColor.orange
    cell?.backgroundColor = UIColor.orange
}

override func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath)
    cell?.contentView.backgroundColor = UIColor.black
    cell?.backgroundColor = UIColor.black
}

enter image description here

答案 2 :(得分:32)

你也可以像这样使用UIAppearance:

UIView *selectionView = [UIView new];
selectionView.backgroundColor = [UIColor redColor];
[[UITableViewCell appearance] setSelectedBackgroundView:selectionView];

这将适用于UITableViewCell的所有实例或您可能拥有的任何子类。只需确保您的单元格的selectionStyle属性设置为UITableViewCellSelectionStyleNone

答案 3 :(得分:14)

比接受的答案更容易:

在你的UITableViewCell子类中:

awakeFromNibinit

self.selectionStyle = UITableViewCellSelectionStyleNone;

然后:

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

    if (highlighted) {
        self.backgroundColor = [UIColor yourHighlightColor];
    }
    else {
        self.backgroundColor = [UIColor yourNormalColor];
    }
}

答案 4 :(得分:8)

在自定义单元格中尝试此操作 -

- (void)awakeFromNib
{
    UIView *selectedBackgroundView = [[UIView alloc] initWithFrame:self.bounds];
    selectedBackgroundView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    selectedBackgroundView.backgroundColor = [UIColor colorWithRed:246.0/255.0 green:95.0/255.0 blue:22.0/255.0 alpha:1.0];
    self.selectedBackgroundView = selectedBackgroundView;
}

答案 5 :(得分:7)

<强>夫特:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.deselectRowAtIndexPath(indexPath, animated: true)
}

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    let selectionColor = UIView() as UIView
    selectionColor.layer.borderWidth = 1
    selectionColor.layer.borderColor = UIColor.blueColor().CGColor
    selectionColor.backgroundColor = UIColor.blueColor()
    cell.selectedBackgroundView = selectionColor
}

Swift 4:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    tableView.deselectRow(at: indexPath, animated: true)
}

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)
{
    let selectionColor = UIView() as UIView
    selectionColor.layer.borderWidth = 1
    selectionColor.layer.borderColor = UIColor.blue.cgColor
    selectionColor.backgroundColor = UIColor.blue
    cell.selectedBackgroundView = selectionColor
}

答案 6 :(得分:3)

根据Milan Cermak的回答,您可以使用UIAppearance

Swift 1.1 / 2.0

let selectionView = UIView()
selectionView.backgroundColor = UIColor.redColor()
UITableViewCell.appearance().selectedBackgroundView = selectionView

答案 7 :(得分:2)

使用Objective C,更改默认值以外的选定单元格背景颜色。无需创建自定义单元格。

  

如果您只想更改单元格的选定颜色,可以执行此操作,请注意,要使其工作,请在Storyboard(或XIB文件)中选择除None之外的所选背景颜色。只需在UITableView Delegate方法中添加以下代码:tableView cellForRowAtIndexPath:

public function editAction($id, Request $request)
{
    $em = $this->getDoctrine()->getManager();
    $budget = $em->getRepository('CDGBundle:Budget')->find($id);

    $products = new ArrayCollection();

    foreach ($budget->getItems() as $item) {
        $products->add($item);
    }

    $form = $this->createForm(BudgetType::class, $budget);
    $form->handleRequest($request);

    if ($form->isValid()) {
        if ($this->get('cdg.budget_updater')->updateProductQtd($budget)) {
            // Here \/
            foreach ($products as $product) {
                if (!$budget->getItems()->contains($product)) {
                    $product->getBudget()->removeItem($product);
                    $em->persist($product);
                }
            }
            // Here /\

            $this->get('cdg.budget_updater')->updatePaymentDates($budget);
            $this->addFlash('notice', 'Orçamento de \'' . $budget->getCustomer() . '\' alterado com sucesso');
        } else {
            $this->addFlash('notice', 'Material(is) esgotado(s). Reveja o seu estoque.');
        }

        return $this->redirectToRoute('budgets');
    }

    return $this->render('budget/edit.html.twig', array(
        'form' => $form->createView(),
        'title' => 'Editar orçamento de ' . $budget->getCustomer()
    ));
}

答案 8 :(得分:1)

自定义UITableViewCell Swift 3.0

override func awakeFromNib() {
        super.awakeFromNib()

        let selectedBackgroundView = UIView();
        selectedBackgroundView.backgroundColor = UIColor.lightGray;
        self.selectedBackgroundView = selectedBackgroundView;
    }

答案 9 :(得分:0)

将以下代码添加到cellForRowAtIndexPath方法

var cell=tableView.dequeueReusableCellWithIdentifier("cell")!
var viewBG=UIView(frame: CGRectMake(0,0,self.view.frame.size.width,50))
viewBG.backgroundColor=UIColor(colorLiteralRed: 71.0/255.0, green: 121.0/255.0, blue: 172.0/255.0, alpha: 1)
cell.selectedBackgroundView=viewBG

答案 10 :(得分:0)

对于swift 3

self.tableView.reloadData()
let selectedCell = tableView.cellForRow(at: indexPath)
selectedCell?.contentView.backgroundColor = UIColor.red

答案 11 :(得分:0)

我最终得到了以下代码。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

  //  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[cellIdArray objectAtIndex:indexPath.row] forIndexPath:indexPath];

    // Configure the cell...
    cell.backgroundView =
    [[UIImageView alloc] init] ;
    cell.selectedBackgroundView =[[UIImageView alloc] init];

    UIImage *rowBackground;
    UIImage *selectionBackground;


    rowBackground = [UIImage imageNamed:@"cellBackgroundDarkGrey.png"];
    selectionBackground = [UIImage imageNamed:@"selectedMenu.png"];

    ((UIImageView *)cell.backgroundView).image = rowBackground;
    ((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;



    return cell;
}

答案 12 :(得分:0)

在Swift 5中:

在您的自定义单元格下,实现此方法。 highlighted表示您按了它但还没有抬起手指。您可以将其与Apple音乐库页面列表进行比较,这是相同的行为。

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        if selected {
            cellLabel.textColor = .white
            cellImageView.tintColor = .white
        } else {
            cellLabel.textColor = .black
            cellImageView.tintColor = .systemPink
        }
    }

    override func setHighlighted(_ highlighted: Bool, animated: Bool) {
        super.setHighlighted(highlighted, animated: animated)
        
        if highlighted {
            cellLabel.textColor = .white
            cellImageView.tintColor = .white
        } else {
            cellLabel.textColor = .black
            cellImageView.tintColor = .systemPink
        }
    }

答案 13 :(得分:-1)

您可以创建自定义UITableViewCell,在其中添加具有单元格大小的UIButton。然后,您可以轻松地为UIButton的TouchDown(悬停)和TouchUpInside事件制作自定义方法,并设置背景。

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        cellButton = [[UIButton alloc] initWithFrame:self.contentView.frame];
        UIImage *cellBackgroundNormal = [UIImage imageNamed:@"cell_menu_normal"];
        UIImageView *cellBackgroundView = [[UIImageView alloc] initWithImage:cellBackgroundNormal];
        self.backgroundView = cellBackgroundView;

        [cellButton addTarget:self action:@selector(hoverCell) forControlEvents:UIControlEventTouchDown];
        [cellButton addTarget:self action:@selector(tapCell) forControlEvents:UIControlEventTouchUpInside];
    }
    return self;
}

- (void)hoverCell
{
    UIImage *cellBackgroundHover = [UIImage imageNamed:@"cell_menu_third_image"];
    UIImageView *cellBackgroundHoverView = [[UIImageView alloc] initWithImage:cellBackgroundHover];
    self.backgroundView = cellBackgroundHoverView;
}

- (void)tapCell
{
    UIImage *cellBackgroundSelected = [UIImage imageNamed:@"cell_menu_selected"];
    UIImageView *cellBackgroundSelectedView = [[UIImageView alloc] initWithImage:cellBackgroundSelected];
    self.backgroundView = cellBackgroundSelectedView;
}

答案 14 :(得分:-4)

您可以在两种不同的背景颜色之间引入一个计时器来设置您想要的时间(如果我理解的话,也可以是1/2秒)?但你可能已经考虑过了:/