2011-03-01 22 views
21

¿Cómo obtener una altura de fila UITableView para el tamaño automático al tamaño de la UITableViewCell?cómo obtener una altura de fila UITableView para auto-tamaño al tamaño de la UITableViewCell?

Suponiendo que estoy creando UITableViewCell en Interface Builder, y su altura es más que el tamaño estándar, ¿cómo puedo obtener la altura de la fila UITableView para autoescalarla? (es decir, a diferencia de tener que medir manualmente la altura en el constructor de interfaz y configurarlo programáticamente)

+0

Puede encontrar la respuesta aquí para iOS 7 y versiones posteriores. http://stackoverflow.com/questions/18746929/using-auto-layout-in-uitableview-for-dynamic-cell-layouts-variable-row-heights – Collin

Respuesta

31

Si todas las celdas son iguales, configure la propiedad rowHeight en UITableView al tamaño de su celda. Si todos son diferentes según el contenido, tendrá que implementar -tableView:heightForRowAtIndexPath: y calcular la altura para cada fila en función de su fuente de datos.

+4

por lo que no hay una varita mágica está teniendo ios de trabajo esto para ti automáticamente entonces? – Greg

+0

Desafortunadamente no en este momento. –

+1

La respuesta de Brian da un buen paso a paso para implementar tableView: heightForRowAtIndexPath –

13

En el xib con su vista de tabla, puede agregar un objeto de celda y vincularlo a una IBOutlet en su código fuente. No lo usarás en ninguna parte, solo usarás esto para obtener la altura de la celda.

Luego, en tableView:heightForRowAtIndexPath: puede usar ese objeto para obtener la altura. No es 100% automático, pero al menos esto le ahorra la molestia de actualizar manualmente su código fuente cuando realiza cambios en la vista de celda en IB.


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return myDummyCellObject.bounds.size.height; 
} 

Si todas las filas son del mismo tipo (celular) se puede establecer mediante programación la propiedad tableView.rowHeight en lugar de aplicar el método delegado anteriormente. Depende de tu escenario

Ah, y asegúrese de no olvidar lanzar myDummyCellObject en -dealloc.

+1

Si ha agregado una propiedad como IBOutlet, no la tramita. Ya no eres responsable de administrarlo. Pero ahora con ARC, todo ese asunto es más o menos discutible. – Kaili

37

http://www.cimgf.com/2009/09/23/uitableviewcell-dynamic-height/ es un gran tutorial para esto.

El bit principal es

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath; 
{ 
    // Get the text so we can measure it 
    NSString *text = [items objectAtIndex:[indexPath row]]; 
    // Get a CGSize for the width and, effectively, unlimited height 
    CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f); 
    // Get the size of the text given the CGSize we just made as a constraint 
    CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap]; 
    // Get the height of our measurement, with a minimum of 44 (standard cell size) 
    CGFloat height = MAX(size.height, 44.0f); 
    // return the height, with a bit of extra padding in 
    return height + (CELL_CONTENT_MARGIN * 2); 
} 
+2

Esta respuesta es dinero. Lo tengo trabajando en minutos. Gracias. –

+0

esto es lo que la gente espera :-) – Akshay

+0

Mi celda personalizada tiene todo tipo de propiedades (por ejemplo, ImageView, Label, TextView). ¿Cuál sería el mío 'NSString * text = [items objectAtIndex: [indexPath row]]' en este caso? –

-1
self.tableView.estimatedRowHeight = 65.0; // Estimate the height you want 
self.tableView.rowHeight = UITableViewAutomaticDimension; // auto change heights for multiple lines cells. 

Al poner en práctica el método UITableViewDataSource requerido:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; 
    cell.textLabel.text = [self.todoArray objectAtIndex:indexPath.row]; 
    cell.textLabel.numberOfLines = 0; // allow multiple lines showing up 

    return cell; 
} 
+0

Esta lógica no debería estar en el método 'cellForRowAtIndexPath'. – Pontus

Cuestiones relacionadas