2011-02-02 18 views
30

Quiero centrar el encabezado en la vista de tabla, sin embargo, tengo 2 problemas. Primero, no tengo la altura correcta y, en segundo lugar, UILabel no se ve como el encabezado predeterminado: fuente, tamaño de fuente, color, etc. ¿Hay una mejor manera de centrarlo, y hay una forma de hacerlo? parece el encabezado predeterminado.Cómo centrar los encabezados de sección de una UITableView

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger) section 
{ 
    //section text as a label 
    UILabel *lbl = [[UILabel alloc] init]; 
    lbl.textAlignment = UITextAlignmentCenter; 

    lbl.text = @"Header"; 
    [lbl setBackgroundColor:[UIColor clearColor]]; 

    return lbl; 
} 

Respuesta

22

también debe aplicar tableView: heightForHeaderInSection para ajustar su altura encabezado:

En el documento UITableViewDelegate referencia del protocolo a encontrar:

tableView: viewForHeaderInSection:

Discusión

El objeto devuelto, por ejemplo, puede sea un objeto UILabel o UIImageView. La vista de tabla ajusta automáticamente la altura del encabezado de sección a para acomodar el objeto de vista devuelto. Este método solo funciona correctamente cuando tableView: heightForHeaderInSection: es también implementado.

Para centrar la etiqueta del encabezado debe especificar el marco de la etiqueta antes de establecer su alineación en el centro. Para conseguir la fuente standart, utilice SystemFontOfSize:

También tenga cuidado está creando fugas una memoria que se supone que devolver una vista autoreleased

Pruebe algo como esto:

UILabel *lbl = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)] autorelease]; 
lbl.textAlignment = UITextAlignmentCenter; 
lbl.font = [UIFont systemFontOfSize:12]; 

Esperanza esta ayuda, Vincent

+0

Gracias, pero todavía tienen que encontrar el tamaño de letra, altura de la etiqueta, etc de la cabecera por defecto real con el fin configúrelo como arriba ... No quiero cambiar nada del encabezado predeterminado excepto la alineación central. Esa alineación izquierda parece tan mala para lo que estoy haciendo. – Mark

+0

He aceptado esta respuesta, ya que fue muy útil y he decidido no utilizar la fuente del encabezado predeterminado del teléfono y usar la mía en su lugar. – Mark

+0

debe ser self.view.frame.size.width en CGRectMake (0, 0, self.view.frame.width, 30) – Stan

-4

Para cambiar la altura, implemente este método:

- (UIView *)tableView:(UITableView *)tableView 
viewForHeaderInSection:(NSInteger)section { return 15; }

No estoy seguro del asunto del encabezado predeterminado, eso debería ser mucho más fácil de lo que es. Tal vez alguien tiene una bonita imagen de fondo que puede usar con una fuente blanca. Pero por lo centrado, intente esto:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,320,15)]; 
label.textAlignment = UITextAlignmentCenter 

label.text = @"Text Should Be Centered"; 
+0

¡Creo que necesita verificar su código antes de enviarlo! la función '-viewForHeaderInSection' devuelve UIView y no puede devolver 15. –

+0

@HamedRajabi Creo que probablemente quise devolver el 15 a cualquier método de altura que se llame: P –

1

probar este

UILabel *tableHeader = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 30)]; 
[tableHeader setText:@"This is header"]; 
[tableHeader setTextAlignment:UITextAlignmentCenter]; 

UITableView *newTable = [[UITableView alloc] initWithFrame:CGRectMake(20, 0, 280, 200) style:UITableViewStylePlain]; 
[newTable setBackgroundColor:[UIColor clearColor]]; 
[newTable setTableHeaderView:tableHeader]; 
self.view = newTable; 
5

aquí está mi versión, tendrá que tomar una captura de pantalla de la base normal de cabecera, y guardar una gran rebanada de 1 píxel de como 'my_head_bg.png' y agrégalo al proyecto. De esta manera, se verá exactamente normal:

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { 
    UILabel *lbl = [[[UILabel alloc] init] autorelease]; 
    lbl.textAlignment = UITextAlignmentCenter; 
    lbl.font = [UIFont fontWithName:@"Helvetica-Bold" size:18]; 
    lbl.text = @"My Centered Header"; 
    lbl.textColor = [UIColor whiteColor]; 
    lbl.shadowColor = [UIColor grayColor]; 
    lbl.shadowOffset = CGSizeMake(0,1); 
    lbl.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"my_head_bg"]]; 
    lbl.alpha = 0.9; 
    return lbl; 
} 
26

esto debería resolver su problema. Probado en Xcode 6/ios8

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    [[UILabel appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil] setTextAlignment:NSTextAlignmentCenter]; 
    return [sectionTitles objectAtIndex:section]; 
} 
+0

Esto funciona muy bien. Anteriormente no había utilizado o visto aparienciaWhenContainedIn como una forma de encontrar algo en la jerarquía de vistas. Truco Ninja! –

+1

¡Este es uno de los mejores trucos que he visto en mi vida! – kygcoleman

+0

funciona! "appearanceWhenContainedIn" podría sacarse del método y colocarse en viewDidLoad – turbo

15

Si se dirige a iOS6 y más tarde usted no tiene que proporcionar su propio punto de vista del cabezal, si lo que desea es centrar el título de cabecera.

Sólo aplicar

- tableView: willDisplayHeaderView: forSection:

y establezca la propiedad textAligment de la etiqueta:

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section 
{ 
    if([view isKindOfClass:[UITableViewHeaderFooterView class]]){ 

     UITableViewHeaderFooterView *tableViewHeaderFooterView = (UITableViewHeaderFooterView *) view; 
     tableViewHeaderFooterView.textLabel.textAlignment = NSTextAlignmentCenter; 
    } 
} 
+3

Esta debería ser la respuesta aceptada. El uso del truco [UILabel appearanceWhenContainedIn: UITableViewHeaderFooterView.class ...] cambiará * todos * sus encabezados en * todas * las vistas de tabla en su aplicación – tiritea

9

respuesta de Volker en Swift:

Si apuntas a iOS6 y luego no tienes que proporcionar tu propia vista de encabezado si solo quieres t o centrar el título del encabezado.

Sólo aplicar

- tableView:willDisplayHeaderView:forSection: 

y establezca la propiedad textAligment de la etiqueta:

func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { 
    if let headerView = view as? UITableViewHeaderFooterView { 
     headerView.textLabel?.textAlignment = .Center 
    } 
} 
2

para que este método se llama primero debe aplicar

titleForHeaderInSection 

continuación tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) methodwillmuch llamarse

Swift Solución:

func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { 
    if let headerView = view as? UITableViewHeaderFooterView { 


     headerView.textLabel?.textAlignment = Localize().isRTL ? .Right : .Left 
     headerView.textLabel?.text = partsDataSource[section] 
     headerView.textLabel?.textColor = UIColor (red: 0.0902, green: 0.2745, blue: 0.2745, alpha: 1.0) 
     headerView.textLabel?.font = UIFont(name: UIDecorator.sharedInstance.PRIMARY_FONT, size: 14.0) 
     headerView.contentView.backgroundColor = UIDecorator.sharedInstance.currentTheme.lightShadeColor 
    } 
} 

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
    return " " 
} 
0

En Xamarin:

 // Center Header 
     public override void WillDisplayHeaderView(UITableView tableView, UIView headerView, nint section) 
     { 
      if (headerView.GetType() == typeof(UITableViewHeaderFooterView)) 
      { 
       UITableViewHeaderFooterView tableViewHeaderFooterView = (UITableViewHeaderFooterView)headerView; 
       tableViewHeaderFooterView.TextLabel.TextAlignment = UITextAlignment.Center; 
      } 
     } 
Cuestiones relacionadas