Вопрос

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

Редактировать:Тот Самый ответ предоставлен DJ-S следует рассматривать для iOS 6 и выше.Принятый ответ устарел.

Это было полезно?

Решение

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

Цель-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;
}

Быстрый:

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 году:

Быстрый 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.

Другие советы

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

Этот метод не включает определение и создание собственного пользовательского представления. В 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/ блог / КСН-как в настройке стол-просмотр заголовка, и-футер-цветы /

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
}

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

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

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

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

Это решение отлично работает с iOS 6.0.

Следующее решение работает для 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()

}

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

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

Если вы не хотите создавать собственный вид, вы также можете изменить цвет следующим образом (требуется 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;
    }
}

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

<Ол>
  • Выбрать вид таблицы
  • Перейти к инспектору атрибутов
  • Элемент списка
  • Прокрутите вниз, чтобы просмотреть подзаголовок
  • Изменить " фон "
  •  Посмотрите здесь

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

    Установите фон и цвет текста области сечения: (Спасибо Уильяму Джокушу и 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]];
        }
    }
    

    Swift 4

    Чтобы изменить цвет фона , цвет текстовой метки и шрифт для представления заголовка раздела UITableView, просто переопределите willDisplayHeaderView для вашего представления таблицы следующим образом:

    override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
            let header = view as! UITableViewHeaderFooterView
            header.backgroundView?.backgroundColor = .white
            header.textLabel?.textColor = .black
            header.textLabel?.font = UIFont(name: "Helvetica-Bold", size: 14)
    } 
    

    Это отлично сработало для меня; надеюсь, это вам тоже поможет!

    Вот как можно добавить изображение в виде заголовка:

    - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
    {
        UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease];
        UIImageView *headerImage = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"top-gery-bar.png"]] autorelease];
    
        headerImage.frame = CGRectMake(0, 0, tableView.bounds.size.width, 30);
    
        [headerView addSubview:headerImage];
    
        return headerView;
    }
    

    Для iOS8 (бета-версия) и Swift выберите нужный вам цвет RGB и попробуйте следующее:

    override func tableView(tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView! {
        var header :UITableViewHeaderFooterView = UITableViewHeaderFooterView()
    
        header.contentView.backgroundColor = UIColor(red: 254.0/255.0, green: 190.0/255.0, blue: 127.0/255.0, alpha: 1)
        return header
    

    }

    ("Переопределение" есть, поскольку я использую UITableViewController вместо обычного UIViewController в моем проекте, но это не обязательно для изменения цвета заголовка раздела)

    Текст вашего заголовка по-прежнему будет виден.Обратите внимание, что вам нужно будет отрегулировать высоту заголовка раздела.

    Удачи.

    SWIFT 2

    Мне удалось успешно изменить цвет фона раздела с добавленным эффектом размытия (что действительно здорово). Чтобы легко изменить цвет фона раздела:

    <Ол>
  • Сначала перейдите в раскадровку и выберите вид таблицы
  • Перейти к инспектору атрибутов
  • Элемент списка
  • Прокрутите вниз, чтобы просмотреть
  • Изменить " Фон "
  • Затем для эффекта размытия добавьте в код:

    override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    
        // This is the blur effect
    
        let blurEffect = UIBlurEffect(style: .Light)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
    
        // Gets the header view as a UITableViewHeaderFooterView and changes the text colour and adds above blur effect
        let headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
        headerView.textLabel!.textColor = UIColor.darkGrayColor()
        headerView.textLabel!.font = UIFont(name: "HelveticaNeue-Light", size: 13)
        headerView.tintColor = .groupTableViewBackgroundColor()
        headerView.backgroundView = blurEffectView
    
    }
    

    Я знаю его ответ, на всякий случай, в Swift используйте следующее

        override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
            let tableViewWidth = self.tableView.bounds
    
            let headerView = UIView(frame: CGRectMake(0, 0, tableViewWidth.size.width, self.tableView.sectionHeaderHeight))
            headerView.backgroundColor = UIColor.greenColor()
    
            return headerView
        }
    

    iOS 8 +

    func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
            tableView.tableHeaderView?.backgroundColor = UIColor.blue()
    }
    

    На основании ответа @Dj S, используя Swift 3. Это прекрасно работает на iOS 10.

    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        // Background color
        view.tintColor = UIColor.black
    
        // Text Color
        let headerView = view as! UITableViewHeaderFooterView
        headerView.textLabel?.textColor = UIColor.white
    }
    

    У меня есть проект, использующий статические ячейки табличного представления, в iOS 7.x. willDisplayHeaderView не срабатывает. Тем не менее, этот метод работает нормально:

    - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    {
        NSLog(@"%s", __FUNCTION__);
        CGRect headerFrame = CGRectMake(x, y, w, h);    
        UIView *headerView = [[UIView alloc] initWithFrame:headerFrame];  
        headerView.backgroundColor = [UIColor blackColor];
    
     -(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 whiteColor]; // substitute your color here
                 content.backgroundColor = color;
                 [castView.textLabel setTextColor:[UIColor blackColor]];
            }
     }
    

    Я думаю, что этот код не так уж плох.

    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(MyHeaderView.reuseIdentifier) as MyHeaderView
        let backgroundView = UIView()
        backgroundView.backgroundColor = UIColor.whiteColor()
        headerView.backgroundView = backgroundView
        headerView.textLabel.text = "hello"
        return headerView
    }
    

    В iOS 7.0.4 я создал пользовательский заголовок с собственным XIB.Ничто из того, что упоминалось здесь раньше, не сработало.Это должен был быть подкласс UITableViewHeaderFooterView для работы с dequeueReusableHeaderFooterViewWithIdentifier: и кажется, что класс очень упрям в отношении цвета фона.Итак, наконец, я добавил UIView (вы могли бы сделать это либо с помощью code, либо IB) с именем customBackgroudView, а затем установил его свойство backgroundColor .В layoutSubviews:Я установил рамку этого представления в bounds (границы). Он работает с 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;
    }
    

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

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

    Если кому-то нужен 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
    }
    

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

    let headerIdentifier = "HeaderIdentifier"
    let header = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: headerIdentifier)
    header.contentView.backgroundColor = UIColor.white
    

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

    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){         
      let tableHeader = view as! UITableViewHeaderFooterView        
      tableHeader.backgroundView?.backgroundColor = UIColor.white     
    }
    

    С 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
    

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

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

      

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

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

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

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

    UITableViewHeaderFooterView.appearance (). backgroundColor = theme.subViewBackgroundColor

    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
        }
    
    Лицензировано под: CC-BY-SA с атрибуция
    Не связан с StackOverflow
    scroll top