Установить цвет фона UITableViewCell - PullRequest
8 голосов
/ 11 июля 2011

Я искал решение, чтобы установить цвет фона для accessoryView на тот же цвет фона, что и для contentView ячейки.

    cell.contentView.backgroundColor = [UIColor colorWithRed:178/255.f green:14/255.f blue:12/255.f alpha:0.05];
    cell.accessoryView.backgroundColor =[UIColor colorWithRed:178/255.f green:14/255.f blue:12/255.f alpha:0.05];

Существует решение, которое работает, но позволяет мне использовать только один цвет для всех ячеек.

cell.contentView.superView.backgroundColor = [UIColor redColor];

Является ли единственным решением не использовать accessoryView и использовать вместо него изображение?

Спасибо!

Ответы [ 6 ]

26 голосов
/ 11 июля 2011
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.backgroundColor = [UIColor greenColor];
}

Используя этот метод UITableViewDelegate, вы можете установить цвет ячеек на разные цвета. Обратите внимание, что Apple явно рекомендует вам внести изменения в свойство backgroundColor в методе tableView:willDisplayCell:ForRowAtIndexPath: в документах , в которых указано:

Если вы хотите изменить цвет фона ячейки, сделайте это в tableView: willDisplayCell: forRowAtIndexPath: метод вашего делегата представления таблицы

Действительно, в iOS 6 изменения свойства откуда-либо еще (например, метод tableView:cellForRowAtIndexPath:) не будут иметь никакого эффекта. Похоже, что это больше не относится к iOS 7, но совет Apple по изменению свойства из tableView:willDisplayCell:ForRowAtIndexPath: остается (без каких-либо объяснений).

Для чередующихся цветов сделайте что-то вроде этого примера:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row % 2) {
        cell.backgroundColor = [UIColor yellowColor];
    } else {
        cell.backgroundColor = [UIColor redColor];    
    }
}
18 голосов
/ 23 февраля 2012

Я тоже некоторое время боролся с этим и прибег к созданию собственного изображения с помощью аксессуара. Но я только что нашел это решение, которое работает хорошо и не требует специального изображения. Хитрость заключается в том, чтобы изменить цвет backgroundView ячейки, а не backgroundColor.

UIView *myView = [[UIView alloc] init];
if (indexPath.row % 2) {
    myView.backgroundColor = [UIColor whiteColor];
} else {
    myView.backgroundColor = [UIColor blackColor];
}
cell.backgroundView = myView;

Нет необходимости изменять цвета фона accessoryView или contentView. Они будут следовать автоматически.


Примечание за 2014 год. Как правило, вы будете использовать - (void) setSelected: (BOOL) selected animated: (BOOL) animated

Итак, у вас будет собственный класс ячеек, и вы установите цвета для нормального / выбранного, как это ...

HappyCell.h
@interface HappyCell : UITableViewCell
@property (strong, nonatomic) IBOutlet UILabel *mainLabel;
etc...
@end

HappyCell.m
@implementation HappyCell

-(id)initWithStyle:(UITableViewCellStyle)style
      reuseIdentifier:(NSString *)reuseIdentifier
    {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
        {
        }
    return self;
    }

-(void)awakeFromNib
    {
    }

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

    if(selected)
        {
        self.backgroundColor = [UIColor redColor];
        .. other setup for selected cell
        }
    else
        {
        self.backgroundColor = [UIColor yellowColor];
        .. other setup for normal unselected cell
        }
    }

@end

// to help beginners.......
// in your table view class, you'd be doing this...

-(NSInteger)tableView:(UITableView *)tableView
      numberOfRowsInSection:(NSInteger)section
    {
    return yourDataArray.count;
    }

-(UITableViewCell *)tableView:(UITableView *)tv
      cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    NSInteger thisRow = indexPath.row;
    ContentsCell *cell = [tv
      dequeueReusableCellWithIdentifier:@"cellName"
      forIndexPath:indexPath]; 
    // "cellName" must be typed in on the cell, the storyboard
    // it's the "identifier", NOT NOT NOT the restorationID

    [cell setupForNumber: thisRow];
    cell.mainLabel.text = yourDataArray[ thisRow ][@"whatever"];
    cell.otherLabel.text = yourDataArray[ thisRow ][@"whatever"];

    return cell;
    }

надеюсь, это кому-нибудь поможет.

7 голосов
/ 11 февраля 2013

Это сработало для меня:

cell.contentView.backgroundColor = [UIColor darkGreyColor];
2 голосов
/ 13 марта 2014

Для всех линий одного цвета

cell.backgroundColor = [UIColor colorWithRed:6.0/255.0 green:122.0/255.0 blue:145.0/255.0 alpha:1.0f];

Для 2 цветов

cell.backgroundColor = [UIColor colorWithRed:6.0/255.0 green:122.0/255.0 blue:145.0/255.0 alpha:1.0f];

    if ((cell.backgroundColor = (indexPath.row % 2 == 0 ? [UIColor colorWithRed:6.0/255.0 green:122.0/255.0 blue:145.0/255.0 alpha:1.0f] : [UIColor colorWithRed:2.0/255.0 green:68.0/255.0 blue:80.0/255.0 alpha:1.0f]))){
        cell.textLabel.textColor = [UIColor whiteColor];

}
0 голосов
/ 28 января 2013

Для любого другого, кто может наткнуться на это и хочет установить свой UITableViewCell фон для рисунка или текстуры вместо сплошного цвета, вы можете сделать это следующим образом:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"pattern.png"]];
}
0 голосов
/ 11 июля 2011

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

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