Cómo encajo texto en una UITableViewCell sin una celda personalizada


Esto es en iPhone 0S 2.0. Las respuestas para 2.1 también están bien, aunque no conozco ninguna diferencia con respecto a las tablas.

Se siente como que debería ser posible obtener texto para envolver sin crear una celda personalizada, ya que un UITableViewCell contiene un UILabel por defecto. Sé que puedo hacer que funcione si creo una celda personalizada, pero eso no es lo que estoy tratando de lograr, quiero entender por qué mi enfoque actual no funciona.

Me he dado cuenta de que la etiqueta se crea bajo demanda (desde el cell admite el acceso a texto e imagen, por lo que no crea la vista de datos hasta que sea necesario), así que si hago algo como esto:

cell.text = @""; // create the label
UILabel* label = (UILabel*)[[cell.contentView subviews] objectAtIndex:0];

Entonces obtengo una etiqueta válida, pero establecer numberOfLines en eso (y lineBreakMode) no funciona - todavía obtengo texto de una sola línea. Hay mucha altura en UILabel para que se muestre el texto - solo estoy devolviendo un valor grande para la altura en heightForRowAtIndexPath.

Author: Vadim Kotov, 2008-09-25

9 answers

Aquí hay una manera más simple, y funciona para mí:

Dentro de su función cellForRowAtIndexPath:. La primera vez que cree su celda:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];
}

Notarás que establezco el número de líneas para la etiqueta en 0. Esto le permite usar tantas líneas como necesite.

La siguiente parte es especificar cuán grande será su UITableViewCell, así que haga eso en su función heightForRowAtIndexPath:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellText = @"Go get some text for your cell.";
    UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0];
    CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
    CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];

    return labelSize.height + 20;
}

Agregué 20 a la altura de mi celda devuelta porque me gusta un poco de búfer alrededor de mi texto.

 273
Author: Tim Rupe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-19 22:17:23

Actualizada la respuesta de Tim Rupe para iOS7:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
    cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellText = @"Go get some text for your cell.";
    UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0];

    NSAttributedString *attributedText =
        [[NSAttributedString alloc]
            initWithString:cellText
            attributes:@
            {
                NSFontAttributeName: cellFont
            }];
    CGRect rect = [attributedText boundingRectWithSize:CGSizeMake(tableView.bounds.size.width, CGFLOAT_MAX)
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                               context:nil];
    return rect.size.height + 20;
}
 15
Author: ddiego,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-06 21:00:32

Un breve comentario / respuesta para registrar mi experiencia cuando tuve el mismo problema. A pesar de usar los ejemplos de código, la altura de la celda de la vista de tabla se estaba ajustando, pero la etiqueta dentro de la celda todavía no se ajustaba correctamente - la solución fue que estaba cargando mi celda desde un archivo NIB personalizado, lo que sucede después de la altura de la celda en ajustado.

Y tenía mi configuración dentro del archivo NIB para no ajustar el texto, y solo tenía 1 línea para la etiqueta; la configuración del archivo NIB ajustes que ajusté dentro del código.

La lección que tomé fue asegurarme de tener siempre en cuenta cuál es el estado de los objetos en cada punto en el tiempo - ¡podrían no haber sido creados todavía! ... hth alguien en la línea.

 3
Author: Richard Le Mesurier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-14 08:31:09

Si vamos a agregar solo texto en la celda UITableView, solo necesitamos dos delegados para trabajar (no es necesario agregar extra UILabels)

1) cellForRowAtIndexPath

2) heightForRowAtIndexPath

Esta solución funcionó para mí: -

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{ 
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:16];
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 0;

    [cell setSelectionStyle:UITableViewCellSelectionStyleGray]; 
    cell.textLabel.text = [mutArr objectAtIndex:indexPath.section];
    NSLog(@"%@",cell.textLabel.text);

    cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow.png" ]];

    return cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{  
    CGSize labelSize = CGSizeMake(200.0, 20.0);

    NSString *strTemp = [mutArr objectAtIndex:indexPath.section];

    if ([strTemp length] > 0)
        labelSize = [strTemp sizeWithFont: [UIFont boldSystemFontOfSize: 14.0] constrainedToSize: CGSizeMake(labelSize.width, 1000) lineBreakMode: UILineBreakModeWordWrap];

    return (labelSize.height + 10);
}

Aquí la cadena mutArr es una matriz mutable de la que estoy obteniendo mis datos.

EDIT: - Aquí está la matriz que tomé.

mutArr= [[NSMutableArray alloc] init];

[mutArr addObject:@"HEMAN"];
[mutArr addObject:@"SUPERMAN"];
[mutArr addObject:@"Is SUPERMAN powerful than HEMAN"];
[mutArr addObject:@"Well, if HEMAN is weaker than SUPERMAN, both are friends and we will never get to know who is more powerful than whom because they will never have a fight among them"];
[mutArr addObject:@"Where are BATMAN and SPIDERMAN"];
 2
Author: Arshad Parwez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-06 13:02:30

Ahora las vistas de tabla pueden tener celdas de tamaño propio. Configure la vista de tabla de la siguiente manera

tableView.estimatedRowHeight = 85.0 //use an appropriate estimate tableView.rowHeight = UITableViewAutomaticDimension

Referencia de Apple

 1
Author: Jason,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-12 02:45:11

Utilizo las siguientes soluciones.

Los datos se proporcionan por separado en un miembro:

-(NSString *)getHeaderData:(int)theSection {
    ...
    return rowText;
}

El manejo se puede hacer fácilmente en cellForRowAtIndexPath. Defina la celda / defina la fuente y asigne estos valores al resultado "celda". Tenga en cuenta que el numberoflines se establece en "0", lo que significa tomar lo que se necesita.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    UIFont *cellFont = [UIFont fontWithName:@"Verdana" size:12.0];
    cell.textLabel.text= [self getRowData:indexPath.section];
    cell.textLabel.font = cellFont;
    cell.textLabel.numberOfLines=0;
    return cell;
}

En heightForRowAtIndexPath, calculo las alturas del texto envuelto. El tamaño del cuerpo estará relacionado con el ancho de su celda. Para iPad esto será 1024. Para iPhone y iPod 320.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIFont *cellFont = [UIFont fontWithName:@"Verdana" size:12.0];
    CGSize boundingSize = CGSizeMake(1024, CGFLOAT_MAX);
    CGSize requiredSize = [[self getRowData:indexPath.section] sizeWithFont:cellFont constrainedToSize:boundingSize lineBreakMode:UILineBreakModeWordWrap];
    return requiredSize.height;    
}
 0
Author: Vincent,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-06 18:02:31

Encontré esto bastante simple y directo :

[self.tableView setRowHeight:whatEvereight.0f];

Por ejemplo:

[self.tableView setRowHeight:80.0f];

Este puede o no ser el mejor enfoque / estándar para hacerlo, pero funcionó en mi caso.

 0
Author: Manish Kr. Shukla,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-24 05:46:42

Creo que esta es una solución mejor y más corta. Formato sólo la UILabel (textLabel) de la celda para calcular automáticamente la altura especificando sizeToFit y todo debería estar bien.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell...
    cell.textLabel.text = @"Whatever text you want to put here is ok";
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 0;
    [cell.textLabel sizeToFit];

    return cell;
}
 -1
Author: dukz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-06 10:43:34

No creo que se pueda manipular una base UITableViewCell's privada UILabel para hacer esto. Puede agregar un nuevo UILabel a la celda usted mismo y usar numberOfLines con sizeToFit para dimensionarlo apropiadamente. Algo como:

UILabel* label = [[UILabel alloc] initWithFrame:cell.frame];
label.numberOfLines = <...an appriate number of lines...>
label.text = <...your text...>
[label sizeToFit];
[cell addSubview:label];
[label release];
 -2
Author: drewh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-06 10:37:53