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

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

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

28 ответов


надеюсь этот метод от 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:

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.


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

этот метод не включает в себя определение и создание собственного пользовательского представления. В 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

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

установка цвета фона в UITableViewHeaderFooterView устарела. Пожалуйста, используйте .


установить цвет фона и текста из раздела: (спасибо 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]];
    }
}

вы можете сделать это на главной.раскадровка примерно за 2 секунды.

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

Have a look here


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

- (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 (Beta) и 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

}

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

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

Удачи.


SWIFT 2

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

  1. сначала перейдите в раскадровку и выберите вид таблицы
  2. перейти к инспектору атрибутов
  3. элемент списка
  4. прокрутите вниз до View
  5. Изменение "Фон"

затем для эффекта размытия добавьте код:

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
    }

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

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


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 (вы можете сделать это с помощью кода или 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;
}

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

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

С RubyMotion / RedPotion, вставьте его в ваш TableScreen:

  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 view: UIView, forSection section: Int) также будет работать, вы можете достичь этого без реализации другого метода делегата. в тебе!--1--> метод, вы можете использовать view.contentView.backgroundColor = UIColor.white вместо view.backgroundView?.backgroundColor = UIColor.white который не работает. (Я знаю это backgroundView является необязательным, но даже когда он есть, это не woking без реализации willDisplayHeaderView


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

UITableViewHeaderFooterView.внешний вид.)(свойство backgroundColor = тема.subViewBackgroundColor