Pregunta

¿Cómo puedo cambiar el color de un encabezado de sección en UITableView?

EDIT : la respuesta proporcionada por DJ-S debe considerarse para iOS 6 y encima. La respuesta aceptada está desactualizada.

¿Fue útil?

Solución

Esperamos que este método del protocolo UITableViewDelegate lo ayude a comenzar:

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

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

Reemplaza [UIColor redColor] con cualquier UIColor que quieras. También es posible que desee ajustar las dimensiones de headerView .

Otros consejos

Esta es una pregunta antigua, pero creo que la respuesta debe actualizarse.

Este método no implica definir y crear su propia vista personalizada. En iOS 6 y versiones posteriores, puede cambiar fácilmente el color de fondo y el color del texto definiendo

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

método de delegado de sección

Por ejemplo:

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

Tomado de mi publicación aquí: https://happyteamlabs.com/ blog / ios-how-to-custom-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
}

Aquí se explica cómo cambiar el color del texto.

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

Puedes hacer esto si quieres un encabezado con color personalizado:

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

Esta solución funciona muy bien desde iOS 6.0.

La siguiente solución funciona para Swift 1.2 con 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()

}

No olvide agregar este fragmento de código del delegado o su vista se cortará o aparecerá detrás de la tabla en algunos casos, en relación con la altura de su vista / etiqueta.

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

Si no desea crear una vista personalizada, también puede cambiar el color de esta manera (requiere 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;
    }
}

Puedes hacerlo en main.storyboard en aproximadamente 2 segundos.

  1. Seleccionar vista de tabla
  2. Ir al inspector de atributos
  3. elemento de lista
  4. Desplácese hacia abajo hasta Ver subtítulo
  5. Cambiar " fondo "

 Echa un vistazo aquí

La configuración del color de fondo en UITableViewHeaderFooterView ha quedado en desuso. Utilice contentView.backgroundColor en su lugar.

Establezca el color de fondo y de texto del área de la sección: (Gracias a William Jockusch y 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

Para cambiar el color de fondo , color de la etiqueta del texto y fuente para la vista de encabezado de una sección de UITableView, simplemente anule willDisplayHeaderView para su vista de tabla como tal:

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

Esto funcionó perfectamente para mí; Espero que te ayude a ti también!

Aquí se explica cómo agregar una imagen en la vista de encabezado:

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

Para iOS8 (Beta) y Swift, elija el color RGB que desee y pruebe esto:

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

}

(La " anulación " está allí desde que estoy & # 180; m usando el UITableViewController en lugar de un UIViewController normal en mi proyecto, pero no es obligatorio para cambiar el color del encabezado de la sección)

El texto de su encabezado aún se verá. Tenga en cuenta que necesitará ajustar la altura del encabezado de la sección.

Buena suerte.

SWIFT 2

Pude cambiar exitosamente el color de fondo de la sección con un efecto de desenfoque agregado (que es realmente genial). Para cambiar fácilmente el color de fondo de la sección:

  1. Primero ve al Guión gráfico y selecciona la Vista de tabla
  2. Ir al inspector de atributos
  3. elemento de lista
  4. Desplácese hacia abajo para ver
  5. Cambiar " Fondo "

Luego, para el efecto de desenfoque, agregue al código:

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

}

Sé que está respondida, por si acaso, en Swift use lo siguiente

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

Basado en la respuesta de @Dj S, usando Swift 3. Esto funciona muy bien en 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
}

Tengo un proyecto que usa celdas de vista de tabla estática, en iOS 7.x. willDisplayHeaderView no se dispara. Sin embargo, este método funciona bien:

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

Creo que este código no es tan malo.

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
}

En iOS 7.0.4, creé un encabezado personalizado con su propio XIB. Nada de lo mencionado aquí antes funcionó. Tenía que ser la subclase del UITableViewHeaderFooterView para trabajar con el dequeueReusableHeaderFooterFooterViewWithIdentifier: y parece que la clase es muy terca con respecto al color de fondo. Así que finalmente agregué una UIView (podría hacerlo con código o IB) con el nombre customBackgroudView, y luego configuré su propiedad backgroundColor. En layoutSubviews: establezco el marco de esa vista en límites. Funciona con iOS 7 y no produce ningún problema técnico.

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

Solo cambia el color de la capa de la vista de encabezado

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

Si alguien necesita swift, conserva el título:

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
}

En mi caso, funcionó así:

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

Solo establece el color de fondo de la vista de fondo:

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

Con RubyMotion / RedPotion, pega esto en tu TableScreen:

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

Funciona como un encanto!

Recibí un mensaje de Xcode a través del registro de la consola

  

[TableView] Configurando el color de fondo en   UITableViewHeaderFooterView ha quedado en desuso. Por favor, establezca una costumbre   UIView con su color de fondo deseado al backgroundView   propiedad en su lugar.

Luego, solo creo una nueva UIView y la coloco como fondo de HeaderView. No es una buena solución, pero es tan fácil como dijo Xcode.

Aunque func tableView (_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) también funcionará, puede lograr esto sin implementar otro método de delegado. en usted func tableView (_ tableView: UITableView, sección viewForHeaderInSection: Int) - > UIView? , puede usar view.contentView.backgroundColor = UIColor.white en lugar de view.backgroundView? .BackgroundColor = UIColor.white que no funciona . (Sé que backgroundView es opcional, pero incluso cuando está allí, esto no se activa sin implementar willDisplayHeaderView

Usando UIAppearance puedes cambiarlo para todos los encabezados en tu aplicación de esta manera:

UITableViewHeaderFooterView.appearance (). backgroundColor = theme.subViewBackgroundColor

Swift 4 lo hace muy fácil. Simplemente agréguelo a su clase y establezca el color según sea necesario.

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

o si es un color simple

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        view.backgroundColor = UIColor.white
    }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top