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

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

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

Ответы [ 30 ]

692 голосов
/ 04 октября 2013

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

Этот метод не включает определение и создание собственного пользовательского представления. В iOS 6 и выше вы можете легко изменить цвет фона и цвет текста, определив

-(void)tableView:(UITableView *)tableView 
    willDisplayHeaderView:(UIView *)view 
    forSection:(NSInteger)section

метод делегата секции

Например:

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    // Background color
    view.tintColor = [UIColor blackColor];

    // Text Color
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    [header.textLabel setTextColor:[UIColor whiteColor]];

    // Another way to set the background color
    // Note: does not preserve gradient effect of original header
    // header.contentView.backgroundColor = [UIColor blackColor];
}

Взято из моего поста здесь: https://happyteamlabs.com/blog/ios-how-to-customize-table-view-header-and-footer-colors/

Swift 3/4

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
    view.tintColor = UIColor.red
    let header = view as! UITableViewHeaderFooterView
    header.textLabel?.textColor = UIColor.white
}
382 голосов
/ 02 мая 2009

Надеюсь, этот метод из протокола UITableViewDelegate поможет вам начать:

Objective-C:

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{
  UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease];
  if (section == integerRepresentingYourSectionOfInterest)
     [headerView setBackgroundColor:[UIColor redColor]];
  else 
     [headerView setBackgroundColor:[UIColor clearColor]];
  return headerView;
}

Swift:

func tableView(_ tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView!
{
  let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 30))
  if (section == integerRepresentingYourSectionOfInterest) {
    headerView.backgroundColor = UIColor.redColor()
  } else {
    headerView.backgroundColor = UIColor.clearColor()
  }
  return headerView
}

Обновлено 2017:

Swift 3:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
    {
        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 30))
        if (section == integerRepresentingYourSectionOfInterest) {
            headerView.backgroundColor = UIColor.red
        } else {
            headerView.backgroundColor = UIColor.clear
        }
        return headerView
    }

Замените [UIColor redColor] на любой UIColor, который вы хотите. Вы также можете настроить размеры headerView.

97 голосов
/ 18 января 2010

Вот как изменить цвет текста.

UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(10, 3, tableView.bounds.size.width - 10, 18)] autorelease];
label.text = @"Section Header Text Here";
label.textColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.75];
label.backgroundColor = [UIColor clearColor];
[headerView addSubview:label];
49 голосов
/ 01 августа 2013

Вы можете сделать это, если вы хотите заголовок с пользовательским цветом:

[[UITableViewHeaderFooterView appearance] setTintColor:[UIColor redColor]];

Это решение прекрасно работает с iOS 6.0.

31 голосов
/ 20 июня 2015

Следующее решение работает для Swift 1.2 с iOS 8 +

override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {

    // This changes the header background
    view.tintColor = UIColor.blueColor()

    // Gets the header view as a UITableViewHeaderFooterView and changes the text colour
    var headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
    headerView.textLabel.textColor = UIColor.redColor()

}
21 голосов
/ 16 января 2012

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

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}
18 голосов
/ 03 октября 2013

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

-(void) tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    if ([view isKindOfClass: [UITableViewHeaderFooterView class]]) {
        UITableViewHeaderFooterView* castView = (UITableViewHeaderFooterView*) view;
        UIView* content = castView.contentView;
        UIColor* color = [UIColor colorWithWhite:0.85 alpha:1.]; // substitute your color here
        content.backgroundColor = color;
    }
}
16 голосов
/ 03 февраля 2016

Вы можете сделать это на main.storyboard примерно за 2 секунды.

  1. Выбрать вид таблицы
  2. Перейти к инспектору атрибутов
  3. Элемент списка
  4. Прокрутите вниз, чтобы просмотреть подзаголовок
  5. Изменить "фон"

Have a look here

16 голосов
/ 02 марта 2013

Установка цвета фона для UITableViewHeaderFooterView устарела. Пожалуйста, используйте contentView.backgroundColor вместо.

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

Установить цвет фона и текста области раздела: (Спасибо William Jockusch и Dj S)

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    if ([view isKindOfClass: [UITableViewHeaderFooterView class]]) {
        UITableViewHeaderFooterView* castView = (UITableViewHeaderFooterView*) view;
        castView.contentView.backgroundColor = [UIColor grayColor];
        [castView.textLabel setTextColor:[UIColor grayColor]];
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...