2011-02-11 10 views
15

Básicamente quiero cambiar la fuente y el color del encabezado de mi sección, así que implemento tableVieW:viewForHeaderInSection. Primero probé este código:¿Por qué tableVieW: viewForHeaderInSection ignora la propiedad de marco de mi UILabel?

-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { 
    UILabel* headerLabel = [[[UILabel alloc] init] autorelease]; 
    headerLabel.frame = CGRectMake(10, 0, 300, 40); 
    headerLabel.backgroundColor = [UIColor clearColor]; 
    headerLabel.textColor = [UIColor blackColor]; 
    headerLabel.font = [UIFont boldSystemFontOfSize:18]; 
    headerLabel.text = @"My section header"; 

    return headerLabel; 
} 

pero por alguna razón la propiedad trama se ignora (estoy hablando de la inserción 10px a la izquierda). Ahora uso lo siguiente:

-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { 
    UIView* headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)] autorelease]; 

    UILabel* headerLabel = [[UILabel alloc] init]; 
    headerLabel.frame = CGRectMake(10, 0, 300, 40); 
    headerLabel.backgroundColor = [UIColor clearColor]; 
    headerLabel.textColor = [UIColor blackColor]; 
    headerLabel.font = [UIFont boldSystemFontOfSize:18]; 
    headerLabel.text = @"My section header"; 

    [headerView addSubview:headerLabel]; 
    [headerLabel release]; 

    return headerView; 
} 

con los resultados deseados. ¿Puede alguien explicarme por qué el segundo enfoque funciona y el primero no?

PS. En ambos casos implemento tableView:heightForHeaderInSection así, volviendo 40,0

Respuesta

25

Eso es debido a que el UITableView establece automáticamente el marco de la vista de encabezamiento que proporcione a

(0, y, table view width, header view height)

y es la posición calculada de la vista y header view height es el valor devuelto por tableView:heightForHeaderInSection:

+0

Entonces realmente necesito el "headerView" en mi código para obtener este recuadro, ¿verdad? – phi

+0

Sí, lo necesitas :) – Jilouc

+0

Genial, gracias :) – phi

0

Tal vez sea mejor no añadir un subvista:

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 
    let view = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20)) 
    let label = UILabel(frame: CGRect(x: 15, y: 5, width: tableView.frame.width, height: 20)) 
    label.text = "\(sections[section].year)" 
    view.addSubview(label) 
    return view 
} 
Cuestiones relacionadas