with viewforheaderinsection titleforheaderinsection custom ios objective-c swift uitableview uitableviewsectionheader

ios - viewforheaderinsection - uitableview with header swift



Cambiar el tamaño de fuente para cabeceras de sección UITableView (9)

¿Puede alguien indicarme la forma más fácil de cambiar el tamaño de fuente del texto en un encabezado de sección UITableView?

Tengo los títulos de la sección implementados usando el siguiente método:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

Luego, entiendo cómo cambiar correctamente la altura del encabezado de la sección con este método:

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

Tengo las celdas UITableView rellenas con este método:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

Sin embargo, estoy estancado en cuanto a cómo aumentar realmente el tamaño de la fuente, o el estilo de fuente, del texto del encabezado de la sección.

¿Alguien puede ayudarme? Gracias.


Con este método, puede establecer el tamaño de fuente, el estilo de fuente y el fondo del encabezado también. hay 2 métodos para esto

Primer método

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{ UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view; header.backgroundView.backgroundColor = [UIColor darkGrayColor]; header.textLabel.font=[UIFont fontWithName:@"Open Sans-Regular" size:12]; [header.textLabel setTextColor:[UIColor whiteColor]]; }

Segundo método

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{ UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 30)]; // myLabel.frame = CGRectMake(20, 8, 320, 20); myLabel.font = [UIFont fontWithName:@"Open Sans-Regular" size:12]; myLabel.text = [NSString stringWithFormat:@" %@",[self tableView:FilterSearchTable titleForHeaderInSection:section]]; myLabel.backgroundColor=[UIColor blueColor]; myLabel.textColor=[UIColor whiteColor]; UIView *headerView = [[UIView alloc] init]; [headerView addSubview:myLabel]; return headerView; }


Lamentablemente, es posible que deba anular esto:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

Pruebe algo como esto:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UILabel *myLabel = [[UILabel alloc] init]; myLabel.frame = CGRectMake(20, 8, 320, 20); myLabel.font = [UIFont boldSystemFontOfSize:18]; myLabel.text = [self tableView:tableView titleForHeaderInSection:section]; UIView *headerView = [[UIView alloc] init]; [headerView addSubview:myLabel]; return headerView; }


Otra forma de hacerlo sería responder al método willDisplayHeaderView . La vista pasada es en realidad una instancia de UITableViewHeaderFooterView .

El siguiente ejemplo cambia la fuente y también centra el texto del título vertical y horizontalmente dentro de la celda. Tenga en cuenta que también debe responder a heightForHeaderInSection para tener en cuenta los cambios en la altura de su encabezado en el diseño de la vista de tabla. (Es decir, si decide cambiar la altura del encabezado en este método willDisplayHeaderView ).

Luego, puede responder al método titleForHeaderInSection para reutilizar este encabezado configurado con diferentes títulos de sección.

C objetivo

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section { UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view; header.textLabel.textColor = [UIColor redColor]; header.textLabel.font = [UIFont boldSystemFontOfSize:18]; CGRect headerFrame = header.frame; header.textLabel.frame = headerFrame; header.textLabel.textAlignment = NSTextAlignmentCenter; }

Swift 1.2

(Nota: si su controlador de vista es un descendiente de un UITableViewController , esto debería declararse como override func ).

override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header:UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView header.textLabel.textColor = UIColor.redColor() header.textLabel.font = UIFont.boldSystemFontOfSize(18) header.textLabel.frame = header.frame header.textLabel.textAlignment = NSTextAlignment.Center }

Swift 3.0

Este código también asegura que la aplicación no se cuelgue si su vista de encabezado no es una UITableViewHeaderFooterView:

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { guard let header = view as? UITableViewHeaderFooterView else { return } header.textLabel?.textColor = UIColor.red header.textLabel?.font = UIFont.boldSystemFont(ofSize: 18) header.textLabel?.frame = header.frame header.textLabel?.textAlignment = .center }


Para iOS 7, uso esto,

-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section { UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view; header.textLabel.font = [UIFont boldSystemFontOfSize:10.0f]; header.textLabel.textColor = [UIColor orangeColor]; }

Aquí está la versión de Swift 3.0 con cambio de tamaño del encabezado

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { if let header = view as? UITableViewHeaderFooterView { header.textLabel!.font = UIFont.systemFont(ofSize: 24.0) header.textLabel!.textColor = UIColor.orange } }


Si bien la respuesta de mosca1337 es una solución correcta, tenga cuidado con ese método. Para un encabezado con texto más largo que una línea, tendrá que realizar los cálculos de la altura del encabezado en tableView:heightForHeaderInSection: que puede ser engorroso.

Un método preferido es usar la API de apariencia:

[[UILabel appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil] setFont:[UIFont boldSystemFontOfSize:28]];

Esto cambiará la fuente, al mismo tiempo que deja la tabla para administrar las alturas.

Para obtener resultados óptimos, haga una subclase de la vista de tabla y añádala a la cadena de contención (en appearanceWhenContainedIn: esté contenida en:) para asegurarse de que la fuente solo se cambie para las vistas de tabla específicas.


Swift 2.0 :

  1. Reemplace el encabezado de sección predeterminado con UILabel completamente personalizable.

Implementa viewForHeaderInSection, así:

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let sectionTitle: String = self.tableView(tableView, titleForHeaderInSection: section)! if sectionTitle == "" { return nil } let title: UILabel = UILabel() title.text = sectionTitle title.textColor = UIColor(red: 0.0, green: 0.54, blue: 0.0, alpha: 0.8) title.backgroundColor = UIColor.clearColor() title.font = UIFont.boldSystemFontOfSize(15) return title }

  1. Altere el encabezado predeterminado (conserva el valor predeterminado).

Implementar willDisplayHeaderView, así:

override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { if let view = view as? UITableViewHeaderFooterView { view.backgroundView?.backgroundColor = UIColor.blueColor() view.textLabel!.backgroundColor = UIColor.clearColor() view.textLabel!.textColor = UIColor.whiteColor() view.textLabel!.font = UIFont.boldSystemFontOfSize(15) } }

Recuerde: si está utilizando celdas estáticas, el encabezado de la primera sección se rellena más alto que otros encabezados de sección debido a la parte superior de UITableView; para arreglar esto:

Implementa heightForHeaderInSection, así:

override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 30.0 // Or whatever height you want! }


Swift 2:

Como OP preguntó, solo ajuste el tamaño, no configurándolo como una fuente en negrita del sistema o lo que sea:

func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { if let headerView = view as? UITableViewHeaderFooterView, textLabel = headerView.textLabel { let newSize = CGFloat(16) let fontName = textLabel.font.fontName textLabel.font = UIFont(name: fontName, size: newSize) } }


Swift 3:

La forma más simple de ajustar solo el tamaño:

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header = view as! UITableViewHeaderFooterView if let textlabel = header.textLabel { textlabel.font = textlabel.font.withSize(15) } }


Swift 4 versión de la answer de Leo Natan es

UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).font = UIFont.boldSystemFont(ofSize: 28)

Si quisiera establecer una fuente personalizada, podría usar

if let font = UIFont(name: "font-name", size: 12) { UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).font = font }