Подтвердить что ты не робот

Как изменить цвет UITableViewCell при выборе?

У меня есть такое меню:

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 для третьего изображения. Если кто-то может помочь мне реализовать это, я бы очень признателен.

4b9b3361

Ответ 1

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

Ответ 2

Вы также можете использовать UIAppearance следующим образом:

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

Это применимо ко всем экземплярам UITableViewCell или любого из его подклассов, которые у вас могут быть. Просто убедитесь, что свойство selectionStyle вашей ячейки не установлено на UITableViewCellSelectionStyleNone.

Ответ 3

iOS 8.0 (и позже) с помощью Swift

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

Ответ 4

Проще, чем принятый ответ:

В подклассе UITableViewCell:

В awakeFromNib или init:

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

Ответ 5

Попробуйте это в пользовательской ячейке -

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

Ответ 6

Swift:

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
}

Ответ 7

На основе ответа Милана Чермака вы можете использовать UIAppearance.

В Swift 1.1 / 2.0:

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

Ответ 8

Используя Objective C, измените выбранный цвет фона ячейки, отличный от значений по умолчанию. Нет необходимости создавать пользовательские ячейки.

Если вы хотите изменить только выбранный цвет ячейки, вы можете это сделать. Помните, что для этого в Раскадке (или XIB файле) вы должны выбрать выбранный цвет фона, отличный от None. Просто добавьте следующий код в метод UITableView Delegate: tableView cellForRowAtIndexPath:

UIView *bgColor = [[UIView alloc] init];

bgColor.backgroundColor = [UIColor yellowColor];

[cell setSelectedBackgroundView:bgColor];

Ответ 9

Пользовательский UITableViewCell Swift 3.0

override func awakeFromNib() {
        super.awakeFromNib()

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

Ответ 10

Добавить следующий код в метод 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

Ответ 11

Для быстрого 3

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

Ответ 12

В итоге я получаю следующий код.

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

Ответ 13

Вы можете создать пользовательский UITableViewCell, в который вы добавите UIButton с размером ячейки. Затем вы можете легко создавать пользовательские методы для событий TouchDown (hover) и TouchUpInside для UIButton и устанавливать фон.

- (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

Вы можете ввести таймер, чтобы установить желаемое время (например, 1/2 с, если я понял) между двумя разными цветами фона? Но вы уже могли подумать об этом:/