UITableView - изменить цвет заголовка раздела - PullRequest
310 голосов
/ 02 мая 2009

Как мне изменить цвет заголовка раздела в UITableView?

РЕДАКТИРОВАТЬ : Ответ , предоставленный DJ-S , следует учитывать для iOS 6 и выше. Принятый ответ устарел.

Ответы [ 30 ]

2 голосов
/ 11 декабря 2018

Просто установите цвет фона для фона:

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){         
  let tableHeader = view as! UITableViewHeaderFooterView        
  tableHeader.backgroundView?.backgroundColor = UIColor.white     
}
2 голосов
/ 09 ноября 2017

В моем случае это работало так:

let headerIdentifier = "HeaderIdentifier"
let header = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: headerIdentifier)
header.contentView.backgroundColor = UIColor.white
2 голосов
/ 29 июля 2016

Если кому-то нужен swift, оставьте заголовок:

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = UIView(frame: CGRect(x: 0,y: 0,width: self.tableView.frame.width, height: 30))
    view.backgroundColor = UIColor.redColor()
    let label = UILabel(frame: CGRect(x: 15,y: 5,width: 200,height: 25))
    label.text = self.tableView(tableView, titleForHeaderInSection: section)
    view.addSubview(label)
    return view
}
2 голосов
/ 13 апреля 2016

Просто измените цвет слоя вида заголовка

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{
  UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0,    tableView.bounds.size.width, 30)] autorelease];
 headerView.layer.backgroundColor = [UIColor clearColor].CGColor
}

2 голосов
/ 16 февраля 2014

В iOS 7.0.4 я создал собственный заголовок с собственным XIB. Ничто из упомянутого здесь раньше не работало. Это должен был быть подкласс UITableViewHeaderFooterView для работы с dequeueReusableHeaderFooterViewWithIdentifier:, и кажется, что класс очень упрям ​​в отношении цвета фона. Наконец, я добавил UIView (вы можете сделать это с помощью кода или IB) с именем customBackgroudView, а затем установил его свойство backgroundColor. В layoutSubviews: я установил рамку этого вида на границы. Работает с iOS 7 и не дает глюков.

// in MyTableHeaderView.xib drop an UIView at top of the first child of the owner
// first child becomes contentView

// in MyTableHeaderView.h
@property (nonatomic, weak) IBOutlet UIView * customBackgroundView;

// in MyTableHeaderView.m
-(void)layoutSubviews;
{
    [super layoutSubviews];

    self.customBackgroundView.frame = self.bounds;
}
// if you don't have XIB / use IB, put in the initializer:
-(id)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    ...
    UIView * customBackgroundView = [[UIView alloc] init];
    [self.contentView addSubview:customBackgroundView];
    _customBackgroundView = customBackgroundView;
    ...
}


// in MyTableViewController.m
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    MyTableHeaderView * header = [self.tableView
                                          dequeueReusableHeaderFooterViewWithIdentifier:@"MyTableHeaderView"];
    header.customBackgroundView.backgroundColor = [UIColor redColor];
    return header;
}
1 голос
/ 04 октября 2017

Я получил сообщение от Xcode через консольный журнал

[TableView] Установка цвета фона на UITableViewHeaderFooterView устарел. Пожалуйста, установите пользовательский UIView с нужным цветом фона для backgroundView свойство вместо.

Затем я просто создаю новый UIView и кладу его в качестве фона HeaderView. Не хорошее решение, но оно простое, как сказал Xcode.

1 голос
/ 18 февраля 2016

С RubyMotion / RedPotion вставьте это в свой настольный экран:

  def tableView(_, willDisplayHeaderView: view, forSection: section)
    view.textLabel.textColor = rmq.color.your_text_color
    view.contentView.backgroundColor = rmq.color.your_background_color
  end

Работает как шарм!

0 голосов
/ 14 января 2019

Swift 4 делает это очень просто. Просто добавьте это в свой класс и установите нужный цвет.

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        view.backgroundColor = UIColor(red: 0.094, green: 0.239, blue: 0.424, alpha: 1.0)
    }

или, если простой цвет

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        view.backgroundColor = UIColor.white
    }
0 голосов
/ 26 января 2018

Используя UIAppearance, вы можете изменить его для всех заголовков в вашем приложении следующим образом:

UITableViewHeaderFooterView.appearance (). BackgroundColor = theme.subViewBackgroundColor

0 голосов
/ 16 января 2018

Хотя func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) также будет работать, вы можете добиться этого без реализации другого метода делегата. в вашем func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? методе вы можете использовать view.contentView.backgroundColor = UIColor.white вместо view.backgroundView?.backgroundColor = UIColor.white, который не работает. (Я знаю, что backgroundView является необязательным, но даже когда он есть, это не пробуждает без реализации willDisplayHeaderView

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