Pregunta

Quiero crear un UITableView con diferentes alturas de fila, y estoy tratando de lograr esto mediante la creación de UILabels dentro de UITableViewCells.

Aquí está mi código hasta ahora:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"EntryCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
    }

    UILabel *textView = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 40)];
    textView.numberOfLines = 0;
    textView.text = [entries objectAtIndex:[indexPath row]];
    [cell.contentView addSubview:textView];
    [textView release];

    return cell;
}

Esto me da 2 líneas de texto por celda. Sin embargo, cada " entrada " tiene un número diferente de líneas y quiero que UITableViewCells cambie de tamaño automáticamente, ajuste el texto según sea necesario, sin cambiar el tamaño de la fuente.

[textView sizeToFit] y / o [cell sizeToFit] no parecen funcionar.

Así es como quiero que se vea el UITableView:

----------------
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
Lorem ipsum
----------------
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
----------------

¿Alguien sabe cómo hacer esto correctamente?

Gracias.

¿Fue útil?

Solución

El UITableViewDelegate define un método opcional heightForRowAtIndexPath, que le ayudará a comenzar. Entonces necesitas usar sizeWithFont.

Aquí se analiza su problema preciso:

http: // www.v2ex.com/2008/09/18/how-to-make-uitableviewcell-have-variable-height/

El tamaño del texto también se trató en este hilo

Otros consejos

Este código funciona para mí. No sé si es perfecto, pero funciona.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    if(indexPath.row<[notesModel numberOfNotes]){
        NSString *cellText = [@"Your text..."];
        UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:12.0];
        CGSize constraintSize = CGSizeMake([UIScreen mainScreen].bounds.size.width - 100, MAXFLOAT);
        CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];

        return labelSize.height + 20;
    }
    else {
        return 20;
    }
}

textView.numberOfLines = 2? numberOflines establece el número máximo de líneas, de modo que tal vez 2 deban hacerlo por ti.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top