Выбран цвет ячейки UITableView?

Я создал пользовательский UITableViewCell. Представление таблицы показывает данные в порядке. Я застрял в том, когда пользователь касается ячейки tableview, тогда я хочу показать цвет фона ячейки, отличный от значений по умолчанию [синий цвет] для выделения выбора ячейки. Я использую этот код, но ничего не происходит:

cell.selectedBackgroundView.backgroundColor=[UIColor blackColor];

30 ответов


Я думаю, что вы были на правильном пути, но в соответствии с определением класса для selectedBackgroundView:

значение по умолчанию равно нулю для ячеек в таблицах простого стиля (UITableViewStylePlain) и не равно нулю для таблиц групп разделов UITableViewStyleGrouped).

поэтому, если вы используете таблицу простого стиля, вам нужно будет выделить новый UIView имея желаемый цвет фона, а затем назначить его selectedBackgroundView.

альтернативно, вы могли бы использовать:

cell.selectionStyle = UITableViewCellSelectionStyleGray;

если все, что вам нужно, это серый фон при выборе ячейки. Надеюсь, это поможет.


нет необходимости в пользовательских ячейках. Если вы хотите изменить только выбранный цвет ячейки, вы можете сделать следующее:

Цель-C:

UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor redColor];
[cell setSelectedBackgroundView:bgColorView];

Свифт:

let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.redColor()
cell.selectedBackgroundView = bgColorView

Swift 3:

let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.red
cell.selectedBackgroundView = bgColorView

Edit: обновлено для ARC

Edit: Добавляет Swift 3


Если у вас есть сгруппированные в таблице только одна ячейка в раздел, просто добавьте эту строку в код: bgColorView.layer.cornerRadius = 10;

UIView *bgColorView = [[UIView alloc] init];
[bgColorView setBackgroundColor:[UIColor redColor]];
bgColorView.layer.cornerRadius = 10;
[cell setSelectedBackgroundView:bgColorView];
[bgColorView release]; 

не забудьте импортировать QuartzCore.


Swift 3: для меня это сработало, когда вы положили его в cellForRowAtIndexPath: метод

let view = UIView()
view.backgroundColor = UIColor.red
cell.selectedBackgroundView = view

таблица выбора ячейки цвет фона может быть установлен с помощью раскадровки:

table view cell selection color None


следующее работает для меня в iOS 8.

Я должен установить стиль выбора в UITableViewCellSelectionStyleDefault пользовательские цвета фона для работы. Если какой-либо другой стиль, пользовательский цвет фона будет проигнорирован. Кажется, что в поведении есть изменения, поскольку предыдущие ответы должны установить стиль в none вместо этого.

полный код для ячейки следующим образом:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"MyCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // This is how you change the background color
    cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    UIView *bgColorView = [[UIView alloc] init];
    bgColorView.backgroundColor = [UIColor redColor];
    [cell setSelectedBackgroundView:bgColorView];        
    return cell;
}

создать пользовательскую ячейку для ячейки таблицы и в пользовательские ячейки класса.м поместите код ниже, он будет работать нормально. Вам нужно разместить желаемое цветное изображение в selectionBackground объектами UIImage.

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    UIImage *selectionBackground = [UIImage imageNamed:@"yellow_bar.png"];
    UIImageView *iview=[[UIImageView alloc] initWithImage:selectionBackground];
    self.selectedBackgroundView=iview;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIView *view = [[UIView alloc] init];
    [view setBackgroundColor:[UIColor redColor]];
    [cell setSelectedBackgroundView:view];
}

нам нужно установить выбранное фоновое представление в этом методе.


Если вы хотите добавить пользовательский выделенный цвет в свою ячейку (и ваша ячейка содержит кнопки, метки,изображения и т. д..) Я сделал следующие шаги:

например, если вы хотите выбрать желтый цвет:

1) Создайте представление, которое соответствует всей ячейке с непрозрачностью 20% (с желтым цветом), вызываемой, например, backgroundselectedView

2) в контроллере ячейки напишите следующее:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
     self.backgroundselectedView.alpha=1;
    [super touchesBegan:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    self.backgroundselectedView.alpha=0;
    [super touchesEnded:touches withEvent:event];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    self.backgroundSelectedImage.alpha=0;
    [super touchesCancelled:touches withEvent:event];
}

Если вы используете пользовательский TableViewCell, вы также можете переопределить awakeFromNib:

override func awakeFromNib() {
    super.awakeFromNib()

    // Set background color
    let view = UIView()
    view.backgroundColor = UIColor.redColor()
    selectedBackgroundView = view
}

расширение Swift 3.0

extension UITableViewCell {
    var selectionColor: UIColor {
        set {
            let view = UIView()
            view.backgroundColor = newValue
            self.selectedBackgroundView = view
        }
        get {
            return self.selectedBackgroundView?.backgroundColor ?? UIColor.clear
        }
    }
}

cell.selectionColor = UIColor.FormaCar.blue


еще один совет к способу Кристиана, чтобы показать закругленный угол фона для сгруппированной таблицы.

Если я использую cornerRadius = 10 для ячейки он показывает фон округленного выделения четырех углов. Это не то же самое с пользовательским интерфейсом table view по умолчанию.

Итак, я думаю о простом способе решить его с помощью структура cornerradius. Как вы можете видеть из приведенных ниже кодов, проверьте местоположение ячейки (верхний, нижний, средний или верхний) и добавьте еще один слой, чтобы скрыть верхний или нижний угол. Это просто показывает точно такой же вид с фоном выбора таблицы по умолчанию.

я протестировал этот код с iPad splitterview. Вы можете изменить положение рамки patchLayer по мере необходимости.

пожалуйста, дайте мне знать, если есть более простой способ достижения аналогичного результата.

if (tableView.style == UITableViewStyleGrouped) 
{
    if (indexPath.row == 0) 
    {
        cellPosition = CellGroupPositionAtTop;
    }    
    else 
    {
        cellPosition = CellGroupPositionAtMiddle;
    }

    NSInteger numberOfRows = [tableView numberOfRowsInSection:indexPath.section];
    if (indexPath.row == numberOfRows - 1) 
    {
        if (cellPosition == CellGroupPositionAtTop) 
        {
            cellPosition = CellGroupPositionAtTopAndBottom;
        } 
        else 
        {
            cellPosition = CellGroupPositionAtBottom;
        }
    }

    if (cellPosition != CellGroupPositionAtMiddle) 
    {
        bgColorView.layer.cornerRadius = 10;
        CALayer *patchLayer;
        if (cellPosition == CellGroupPositionAtTop) 
        {
            patchLayer = [CALayer layer];
            patchLayer.frame = CGRectMake(0, 10, 302, 35);
            patchLayer.backgroundColor = YOUR_BACKGROUND_COLOR;
            [bgColorView.layer addSublayer:patchLayer];
        } 
        else if (cellPosition == CellGroupPositionAtBottom) 
        {
            patchLayer = [CALayer layer];
            patchLayer.frame = CGRectMake(0, 0, 302, 35);
            patchLayer.backgroundColor = YOUR_BACKGROUND_COLOR;
            [bgColorView.layer addSublayer:patchLayer];
        }
    }
}

хочу отметить, что редактор XIB предлагает вам следующие стандартные варианты:

раздел: синий / серый / нет

(правый столбец с параметрами, 4-я вкладка, первая группа "ячейка таблицы", 4-я подгруппа, 1-й из 3-х элементов читает "выбор")

вероятно, то, что вы хотите сделать, может быть достигнуто путем выбора правильного стандартный вариант.


в соответствии с пользовательским цветом для выбранной ячейки в UITableView, - отличное решение как в ответ

просто чтобы добавить к этому, вы объявляете Свик х ответ в конфигурации ячейки обычно под:

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

и для дополнительного эффекта вместо системных цветов вы можете использовать значения RGB для пользовательского цветового вида. В моем коде это то, как я этого достиг:

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

} 

 static NSString *CellIdentifier = @"YourCustomCellName";
 MakanTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

// Configure the cell...

if (cell == nil) {

cell = [[[NSBundle mainBundle]loadNibNamed:@"YourCustomCellClassName" owner:self options:nil]objectAtIndex:0];
                    } 

UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor colorWithRed:255.0/256.0 green:239.0/256.0 blue:49.0/256.0 alpha:1];
bgColorView.layer.cornerRadius = 7;
bgColorView.layer.masksToBounds = YES;
[cell setSelectedBackgroundView:bgColorView];


return cell;

}

Дайте мне знать, если это работает для вас также. Вы можете возиться с cornerRadius номер для эффектов на углах выбранной ячейки.


У меня немного другой подход, чем у всех остальных, который отражает выбор на ощупь, а не После выбора. У меня есть подкласс UITableViewCell. Все, что вам нужно сделать, это установить цвет фона в сенсорных событиях, который имитирует выбор на ощупь, а затем установить цвет фона в функции setSelected. Установка цвета фона в функции selSelected позволяет отменить выбор ячейки. Обязательно передайте событие touch супер, в противном случае ячейка не будет действовать так, как если бы она была выбрана.

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    self.backgroundColor = UIColor(white: 0.0, alpha: 0.1)
    super.touchesBegan(touches, withEvent: event)
}

override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
    self.backgroundColor = UIColor.clearColor()
    super.touchesCancelled(touches, withEvent: event)
}

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

    // Configure the view for the selected state
    self.backgroundColor = selected ? UIColor(white: 0.0, alpha: 0.1) : UIColor.clearColor()
}

чтобы добавить фон для всех ячеек (используя ответ Мацея):

for (int section = 0; section < [self.tableView numberOfSections]; section++) {
        for (int row = 0; row < [self.tableView numberOfRowsInSection:section]; row++) {
            NSIndexPath* cellPath = [NSIndexPath indexPathForRow:row inSection:section];
            UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:cellPath];

            //stuff to do with each cell
            UIView *bgColorView = [[UIView alloc] init];
            bgColorView.backgroundColor = [UIColor redColor];
            [cell setSelectedBackgroundView:bgColorView];
        }
    } 

переопределить UITableViewCell ' s setSelected тоже работает.

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

    // Set background color
    let view = UIView()
    view.backgroundColor = UIColor.redColor()
    selectedBackgroundView = view
}

для тех, кто просто хочет избавиться от выбранного по умолчанию серого фона, поместите эту строку кода в свой cellforrowatindexpath func:

yourCell.selectionStyle = .None

для Swift 3.0:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = super.tableView(tableView, cellForRowAt: indexPath)

    cell.contentView.backgroundColor = UIColor.red
}

в Swift 4 вы также можете установить цвет фона ячейки таблицы глобально (взято из здесь):

let backgroundColorView = UIView()
backgroundColorView.backgroundColor = UIColor.red
UITableViewCell.appearance().selectedBackgroundView = backgroundColorView

вот важные части кода, необходимые для сгруппированной таблицы. При выборе любой из ячеек в разделе Первая строка меняет цвет. Без первоначальной установки cellselectionstyle в none происходит двойная перезагрузка annonying, когда пользователь нажимает row0, где ячейка изменяется на bgColorView затем исчезает и перезагружает bgcolorview снова. Удачи и дайте мне знать, если есть более простой способ сделать это.

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

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    if ([indexPath row] == 0) 
    {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        UIView *bgColorView = [[UIView alloc] init];
        bgColorView.layer.cornerRadius = 7;
        bgColorView.layer.masksToBounds = YES;
        [bgColorView setBackgroundColor:[UIColor colorWithRed:.85 green:0 blue:0 alpha:1]];
        [cell setSelectedBackgroundView:bgColorView];

        UIColor *backColor = [UIColor colorWithRed:0 green:0 blue:1 alpha:1];
        cell.backgroundColor = backColor;
        UIColor *foreColor = [UIColor colorWithWhite:1 alpha:1];
        cell.textLabel.textColor = foreColor;

        cell.textLabel.text = @"row0";
    }
    else if ([indexPath row] == 1) 
    {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        UIColor *backColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1];
        cell.backgroundColor = backColor;
        UIColor *foreColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1];
        cell.textLabel.textColor = foreColor;

        cell.textLabel.text = @"row1";
    }
    else if ([indexPath row] == 2) 
    {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        UIColor *backColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1];
        cell.backgroundColor = backColor;
        UIColor *foreColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1];
        cell.textLabel.textColor = foreColor;

        cell.textLabel.text = @"row2";
    }
    return cell;
}

#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:[indexPath section]];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:path];
    [cell setSelectionStyle:UITableViewCellSelectionStyleBlue];

    [tableView selectRowAtIndexPath:path animated:YES scrollPosition:UITableViewScrollPositionNone];

}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tvStat cellForRowAtIndexPath:indexPath];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}

#pragma mark Table view Gestures

-(IBAction)singleTapFrom:(UIGestureRecognizer *)tapRecog
{

    CGPoint tapLoc = [tapRecog locationInView:tvStat];
    NSIndexPath *tapPath = [tvStat indexPathForRowAtPoint:tapLoc];

    NSIndexPath *seleRow = [tvStat indexPathForSelectedRow];
    if([seleRow section] != [tapPath section])
        [self tableView:tvStat didDeselectRowAtIndexPath:seleRow];
    else if (seleRow == nil )
        {}
    else if([seleRow section] == [tapPath section] || [seleRow length] != 0)
        return;

    if(!tapPath)
        [self.view endEditing:YES];

    [self tableView:tvStat didSelectRowAtIndexPath:tapPath];
}

Я использую ниже подход и отлично работает для меня,

class MyTableViewCell : UITableViewCell {

                var defaultStateColor:UIColor?
                var hitStateColor:UIColor?

                 override func awakeFromNib(){
                     super.awakeFromNib()
                     self.selectionStyle = .None
                 }

// if you are overriding init you should set selectionStyle = .None

                override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
                    if let hitColor = hitStateColor {
                        self.contentView.backgroundColor = hitColor
                    }
                }

                override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
                    if let defaultColor = defaultStateColor {
                        self.contentView.backgroundColor = defaultColor
                    }
                }

                override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
                    if let defaultColor = defaultStateColor {
                        self.contentView.backgroundColor = defaultColor
                    }
                }
            }

в случае пользовательского класса клеток. Просто переопределите:

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

    // Configure the view for the selected state

    if (selected) {
        [self setBackgroundColor: CELL_SELECTED_BG_COLOR];
        [self.contentView setBackgroundColor: CELL_SELECTED_BG_COLOR];
    }else{
        [self setBackgroundColor: [UIColor clearColor]];
        [self.contentView setBackgroundColor: [UIColor clearColor]];
    }
}

это легко, когда стиль представления таблицы прост, но в стиле группы это небольшая проблема, я решаю ее:

CGFloat cellHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kGroupTableViewCellWidth+2, cellHeight)];
view.backgroundColor = kCommonHighlightedColor;
cell.selectedBackgroundView = view;
[view release];
UIRectCorner cornerFlag = 0;
CGSize radii = CGSizeMake(0, 0);
NSInteger theLastRow = --> (yourDataSourceArray.count - 1);
if (indexPath.row == 0) {
    cornerFlag = UIRectCornerTopLeft | UIRectCornerTopRight;
    radii = CGSizeMake(10, 10);
} else if (indexPath.row == theLastRow) {
    cornerFlag = UIRectCornerBottomLeft | UIRectCornerBottomRight;
    radii = CGSizeMake(10, 10);
}
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:cornerFlag cornerRadii:radii];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = maskPath.CGPath;
view.layer.mask = shapeLayer;

отметил kGroupTableViewCellWidth, я определяю его как 300, это ширина ячейки таблицы группы в iPhone


[cell setSelectionStyle:UITableViewCellSelectionStyleGray];

убедитесь, что вы использовали указанную выше строку для использования эффекта выбора


override func setSelected(selected: Bool, animated: Bool) {
    // Configure the view for the selected state

    super.setSelected(selected, animated: animated)
    let selView = UIView()

    selView.backgroundColor = UIColor( red: 5/255, green: 159/255, blue:223/255, alpha: 1.0 )
    self.selectedBackgroundView = selView
}

Я использую iOS 9.3 и устанавливаю цвет через раскадровку или настройку cell.selectionStyle не работал для меня, но код ниже работал:

UIView *customColorView = [[UIView alloc] init];
customColorView.backgroundColor = [UIColor colorWithRed:55 / 255.0 
                                                  green:141 / 255.0 
                                                   blue:211 / 255.0 
                                                  alpha:1.0];
cell.selectedBackgroundView = customColorView;

return cell;

Я нашел это решение здесь.


попробуйте следующий код.

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

/ / Swift Версия:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell


        cell.selectedBackgroundView = UIImageView()
        cell.backgroundView=UIImageView()

        let selectedBackground : UIImageView = cell.selectedBackgroundView as! UIImageView
        selectedBackground.image = UIImage.init(named:"selected.png");

        let backGround : UIImageView = cell.backgroundView as! UIImageView
        backGround.image = UIImage.init(named:"defaultimage.png");

        return cell


    } 

Swift 4.x

чтобы изменить цвет фона выбора на anyColour, используйте Swift расширение

создать расширение ячейки UITableView, как показано ниже

extension UITableViewCell{

    func removeCellSelectionColour(){
        let clearView = UIView()
        clearView.backgroundColor = UIColor.clear
        UITableViewCell.appearance().selectedBackgroundView = clearView
    } 

}
вызов removeCellSelectionColour () С экземпляр камеру.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView reloadData];
    UITableViewCell *cell=(UITableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
    [cell setBackgroundColor:[UIColor orangeColor]];
}