Pregunta

¿Cómo se modificaría el siguiente fragmento de código (en un tableView: cellForRowAtIndexPath: UITableViewController) desde el " 09a - PrefsTable " receta del Capítulo 6 del Libro de cocina para desarrolladores de iPhone:

if (row == 1) { 
    // Create a big word-wrapped UILabel 
    cell = [tableView dequeueReusableCellWithIdentifier:@"libertyCell"]; 
    if (!cell) { 
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"libertyCell"] autorelease]; 
        [cell addSubview:[[UILabel alloc] initWithFrame:CGRectMake(20.0f, 10.0f, 280.0f, 330.0f)]]; 
    } 
    UILabel *sv = [[cell subviews] lastObject]; 
    sv.text =  @"When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation."; 
    sv.textAlignment = UITextAlignmentCenter; 
    sv.lineBreakMode = UILineBreakModeWordWrap; 
    sv.numberOfLines = 9999; 
    return cell; 
} 

... para dimensionar el " sv " Subvista de UILabel y la '' celda '' ¿Se puede ajustar el tamaño de UITableViewCell para que se ajuste al texto (y trabajar con más o menos texto y otros tipos de alineación de texto)? & nbsp; Miré el método de UILabel textRectForBounds: limitedToNumberOfLines: pero la documentación indica que no se debe llamar directamente (y solo se debe anular). & nbsp; Experimenté con el método UIView sizeToFit, sin éxito.

Actualización: Hice una nueva pregunta sobre mi problema con NSString -sizeWithFont: forWidth: lineBreakMode: method .

¿Fue útil?

Solución

Tuve que hacer esto lo suficiente como para extender UILabel para que lo haga por mí:

@interface UILabel (BPExtensions)
- (void)sizeToFitFixedWidth:(CGFloat)fixedWidth;
@end

@implementation UILabel (BPExtensions)


- (void)sizeToFitFixedWidth:(CGFloat)fixedWidth
{
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, fixedWidth, 0);
    self.lineBreakMode = NSLineBreakByWordWrapping;
    self.numberOfLines = 0;
    [self sizeToFit];
}
@end

para tener una etiqueta que tenga una altura variable de varias líneas pero un ancho fijo solo:

[myLabel sizeToFitFixedWidth: kSomeFixedWidth];

Otros consejos

Debe usar el método -sizeWithFont: forWidth: lineBreakMode: de NSString para recuperar las métricas de tamaño asociadas para su etiqueta.

Además, cambie la propiedad numberOfLines a 0 si va a usar ese código.

El código de NSString de -sizeWithFont: forWidth: lineBreakMode: no realiza realmente el ajuste de palabra. En su lugar, use -sizeWithFont: restricinedToSize: lineBreakMode: para obtener un valor de ancho Y altura precisos para la cadena.

Prueba esto:

sv.text =  @"When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation."; 
sv.textAlignment = UITextAlignmentCenter; 
sv.lineBreakMode = UILineBreakModeWordWrap; 
sv.numberOfLines = 0;
[sv sizeToFit]; 

Además, deberá implementar el método UITableViewDelegate:

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

Y haga que devuelva una altura de celda total ajustada para el campo de texto redimensionado.

Otra nota: el tamaño para ajustar realmente debería funcionar, si tiene el número de líneas establecido en 0 como se mencionó anteriormente. Le devolvería un tamaño con la altura aumentada para acomodar el texto ajustado con texto establecido en la etiqueta y el ancho establecido con el ancho original de la etiqueta.

Sin embargo, esto no le ayudará, ya que necesita obtener el tamaño en heightForRow antes de que se obtenga la celda, por lo que es mejor calcular la altura necesaria (y probablemente almacenar en caché ese cálculo para no ralentizar el procesamiento de la tabla)

Aquí hay un poco de código que utilizo:

CGSize textSize = [myLabel.text sizeWithFont:myLabel.font];

Tuve un problema similar, tuve un UITableViewCell que fue diseñado en StoryBoards como una celda estática. Utilicé [super tableView: cellForRowAtIndexPath:] para obtenerlo. Así que quería cambiar el tamaño de la UILabel " detailTextLabel " por lo que se ajusta al texto que le puse. El estilo era "Detalle correcto".

Acabo de configurar el texto en mi tableView: cellForRowAtIndexPath: . Y que en tableView: heightForRowAtIndexPath: devolví

UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
return cell.detailTextLabel.frame.size.height

Tenía una cuerda larga. Y finalmente tenía una celda ancha con 4 líneas de texto en la etiqueta.

Tuve un problema similar. Resolví esto.

En el método cellForRowAtIndexPath establezca el tamaño de fuente a lo que desee.

cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;    
[cell.textLabel setFont:[UIFont systemFontOfSize:14.0]];
[cell.textLabel sizeToFit];

Y en el método heightForRowAtIndexPath aumentar el tamaño de la fuente.

    CGFloat height;

    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    NSString *text = cell.detailTextLabel.text;
    CGSize constraint = CGSizeMake(320, 20000.0f);
    CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:20.0]     constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
    CGFloat calHeight = MAX(size.height, 44.0f);
    height =  calHeight + (CELL_CONTENT_MARGIN * 2);

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