2011-05-31 10 views
6

Necesitaré personalizar la sección del encabezado de un UITableViewController donde para cada sección se devuelve un texto de encabezado diferente (también se obtienen datos del origen de datos). Esto se logra usando lo siguiente:Personalizar la sección del encabezado para UITableViewController

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    NSArray *temp = [listOfMBeans allKeys]; 
    DLog(@"MBean details: %@", temp); 
    NSString *title = [temp objectAtIndex:section]; 
    DLog(@"Header Title: %@", title); 
    return title; 
}; 

Esto funciona bien y puedo ver el resultado esperado. Sin embargo tengo que cambiar también el tamaño de fuente del texto y después de ver las preguntas similares He implementado el siguiente:

- (UIView *) tableview:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{ 
    DLog(@"Custom Header Section Title being set"); 
    UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease]; 

    UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease]; 
    label.text = [tableView.dataSource tableView:tableView titleForHeaderInSection:section]; 
    label.backgroundColor = [UIColor clearColor]; 
    label.font = [UIFont boldSystemFontOfSize:14]; 

    [headerView addSubview:label]; 
    return headerView; 
} 

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

Sin embargo parece que el código no se llama. Según tengo entendido, UITableViewController se configura de manera predeterminada como delegado, pero parece que estoy equivocado.

El UITableViewController se crea de esta manera (como parte de los datos jerárquicos):

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    ProjectDetails *detailViewController = [[ProjectDetails alloc] initWithStyle:UITableViewStyleGrouped]; 
    detailViewController.project = [listOfMetrics objectAtIndex:indexPath.row]; 

    // Push the detail view controller. 
    [[self navigationController] pushViewController:detailViewController animated:YES]; 
    [detailViewController release]; 
} 

¿Qué cambios, que debe hacer para hacer este trabajo? Gracias.

+0

en realidad no es claro para mí, que lo que está pidiendo? – rptwsthi

+0

asegúrate de configurar un nuevo delegado de vista de tabla, quizás en el método init de 'projectDetails'. – theiOSDude

+0

@rptwsthi Básicamente, cómo hacer que mi UITableViewController ProjectDetails llame a viewForHeaderInSection para personalizar la vista de encabezado –

Respuesta

3

Puede establecer explícitamente el delegado:

detailViewController.tableView.delegate = detailViewController; 

O bien, puede hacerlo en la función inicial del controlador.

EDIT: su método init debe ajustarse a la inicial canónica. Además, me parece que no ha creado su UITableView. Tratar de utilizar este código:

- (id)initWithStyle:(UITableViewStyle)style { 
    if ((self = [super initWithStyle:style])) { 
     self.tableView = [[[UITableView alloc] initWithFrame:self.view.bounds] autorelease]; 
     self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth UIViewAutoresizingFlexibleHeight; 
     self.tableView.delegate = self; 
    } 
    return self; 
} 

Por supuesto, también se puede hacer todo esto en un archivo semilla ...

+0

Ok Definitivamente me perdí en este punto :(He intentado ambas soluciones pero no suerte. En ProjectDetails.m He agregado este estilo '- (id) initWithStyle: (UITableViewStyle) { UITableViewController * tvc = [s uper initWithStyle: style]; tvc.tableView.delegate = self; return tvc; } 'pero aún no puedo ver' - (UIView *) tabla vista: (UITableView *) tableView viewForHeaderInSection: (NSInteger) sección' –

+0

Ver mi edición, por favor ... – sergio

+0

Ahh ese es el truco ... tendré que crear mi propio UITableView y no usar el que genera por defecto. ¡Muchas gracias! –

2

Puede probar esto: en su ProjectDetails.h declare un UIView *tableHeader y también un método de acceso - (UIView *)tableHeader;. A continuación, en el archivo de implementación:

- (UIView *)tableHeader { 
    if (tableHeader) 
     return tableHeader; 

    tableHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)]; 
    // addlabel 
    return tableHeader; 
} 

En viewDidLoad, llame a: self.tableView.tableHeaderView = [self tableHeader];

no creo que tendrá que utilizar el método heightForHeaderInSection.

+0

Hola Mark, lo he intentado pero aunque puedo ver que el método se llama encabezado de sección no se cambia :(Todavía veo el texto de mi sección que sale del deafult '(NSString *) tableView: (UITableView *) tableView titleForHeaderInSection: (NSInteger) sección' –

+0

Si está intentando crear encabezados personalizados para varias secciones en tableView, entonces es posible que haya malentendido su pregunta. –

+0

Sí, para cada sección Tengo un encabezado con texto diferente (que también sale de la fuente de datos). Editaré la pregunta original para aclarar este punto. –

11

Esta pregunta es antiguo, pero quería compartir mi código. Estoy usando una vista de celda de tabla habitual para los encabezados de mi sección. Lo he diseñado con el constructor de interfaz e implementado el siguiente método delegado.

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: @"Header"]; 
    cell.textLabel.text = @"test"; 
    return cell; 
} 
+0

¿por qué está utilizando la celda para la vista de encabezado? ¿Estás utilizando dos tipos de células (encabezado/cuerpo) para algún tipo de lista anidada? Me pregunto cómo las aplicaciones de los sns implementan la vista de lista anidada y si estás haciendo algo similar. – eugene

+2

@Eugene porque puede diseñar celdas en IB. Sí, tengo listas anidadas y al menos dos prototipos de células 'encabezado' y 'elemento'. No estoy seguro de cómo otros implementan este enfoque. – cocoafan

+1

+1 para un enfoque inteligente y simple –

3

Así es como se obtiene la sección de barebones ver utilizando los métodos UITableViewDelegate:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
    { 
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 40.0)]; 
    header.backgroundColor = [UIColor grayColor]; 

    UILabel *textLabel = [[UILabel alloc] initWithFrame:header.frame]; 
    textLabel.text = @"Your Section Title"; 
    textLabel.backgroundColor = [UIColor grayColor]; 
    textLabel.textColor = [UIColor whiteColor]; 

    [header addSubview:textLabel]; 

    return header; 
} 

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section 
    { 
    return 40.0; 
    } 
+0

Dado que ha establecido que el marco de la etiqueta es igual al marco de la vista, la instrucción backgroundColor del encabezado es inútil ya que se reemplazó por el textLabel backgroundColor one – Max

Cuestiones relacionadas