uitableviewcontroller uitableviewcell ios uitableview cocoa-touch

ios - uitableviewcontroller - uitableviewcell lifecycle



UITableView-cambiar el color del encabezado de la sección (28)

Aquí es 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; }

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

EDITAR : La respuesta proporcionada por DJ-S debe considerarse para iOS 6 y superior. La respuesta aceptada está desactualizada.


Aquí es 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];


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


Basado en @Dj S answer, 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 }


Con RubyMotion / RedPotion, pegue esto en su 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 de maravilla!


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 de UITableViewHeaderFooterView para trabajar con dequeueReusableHeaderFooterViewWithIdentifier: y parece que la clase es muy obstinada en relación con el 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 da fallas.

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


En mi caso, funcionó así:

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


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


Establezca el fondo y el color del 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]]; } }


La configuración del color de fondo en UITableViewHeaderFooterView ha quedado en desuso. Por favor, use contentView.backgroundColor en contentView.backgroundColor lugar.


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


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

}

(El "reemplazo" está allí porque estoy 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 todavía se verá. Tenga en cuenta que necesitará ajustar la altura del encabezado de la sección.

Buena suerte.


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.


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 el fondo"


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

[TableView] La configuración del color de fondo en UITableViewHeaderFooterView ha quedado en desuso. Por favor, establezca una UIView personalizada con su color de fondo deseado en la propiedad backgroundView en su lugar.

Luego simplemente 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.


Sé que su respuesta, por si acaso, en Swift utilizamos las siguientes

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 }


Si alguien necesita swift, mantiene 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 }


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


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 }


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


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

UITableViewHeaderFooterView.appearance (). BackgroundColor = theme.subViewBackgroundColor


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 el color de fondo de la sección fácilmente:

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


Swift 4

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

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 también!


iOS 8+

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


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

C objetivo:

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

Rápido:

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 }

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


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