2011-09-28 18 views
7

He buscado y buscado a través de blogs interminables y artículos sobre cómo determinar una altura dinámica para una UITableViewCell personalizada y su texto detallado. Realmente me ha costado encontrar una buena documentación sobre esto.Personalizado UITableView Altura de celda dinámica

Lo que necesito hacer es tener la célula crezca de acuerdo con el texto interior, pero nunca pasan debajo de una altura de 70

He probado varios de las respuestas para este tipo de pregunta aquí en StackOverflow pero ninguno de ellos funcionó. Toda mi aplicación está casi terminada, pero realmente necesito lograr esto antes de lanzar y es problemático.

Esto es lo que estoy intentando, pero acabo de recibir un montón de células superpuestas entre sí. Según lo que he leído, necesito encontrar el marco si la celda personalizada o la vista de texto en la celda también, pero no estoy seguro de cómo hacer eso o mezclarlos todos juntos para devolver una altura.

Cualquier ayuda sería muy apreciada ¡Gracias! Método

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

    CGSize aSize; 
aSize = [[(Tweet*)[tweets objectAtIndex:indexPath.row]tweet] sizeWithFont:[UIFont 
systemFontOfSize:14] 
      constrainedToSize:CGSizeMake(300.0, 1000.0) 
       lineBreakMode:UILineBreakModeTailTruncation]; 

return aSize.height; 
} 
+0

http://imageshack.us/photo/my-images/508/screenshot2011092816313.png – FreeAppl3

+0

La imagen muestra lo que me pasa con casi todos los métodos que intento! Parece que está obteniendo el tamaño de cada cadena de texto pero no cambia el tamaño de las celdas – FreeAppl3

Respuesta

18

tuve un problema similar hace un tiempo y esto me ha ayudado enormemente.

#define PADDING 10.0f 
- (CGFloat)tableView:(UITableView *)t heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
    NSString *text = [self.items objectAtIndex:indexPath.row]; 
    CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(self.tableView.frame.size.width - PADDING * 3, 1000.0f)]; 

    return textSize.height + PADDING * 3; 
} 
+0

Tuve que reemplazar el primer "PADDING * 3" con "PADDING * 4" y el último "PADDING * 3" con "PADDING * 2" .... –

+0

Sí tendrá que ajustarse de acuerdo a sus necesidades específicas, pero esto es solo una base. – WrightsCS

+5

Debe tener en cuenta que 'sizeWithFont: constrainedToSize:' está en desuso en iOS 7, por lo que debe usar 'boundingRectWithSize: options: attributes: context:' –

-4

Uso UITableViewDelegate:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
// here you need to get height of your textlabel in your custom cell. 
MyCustomCell *myCell = (MyCustomCell *)[tableView cellForRowAtIndexPath:indexPath]; 
return myCell.myTextLabel.frame.size.height + 20; 
} 

Algo como esto

+0

La primera línea de código [tableView cellForRowAtIndexPath: indexPath]; simplemente hace que la aplicación se cuelgue ... gracias por la respuesta, aunque – FreeAppl3

+0

Se bloquea porque todavía no tienes células. No pensé en eso, lo siento. La respuesta WrightsCS debería ayudar –

+0

Creó, "EXE_BAD_ACCESS" – HelloWorld

3

Hola por lo que van a necesitar para almacenar la lista de cadenas en una NSArray y luego se va a necesitar calcule la altura del nsstring usando sizeWithFont: constrainedToSize: la documentación se encuentra aquí http://developer.apple.com/library/ios/#documentation/UIKit/Reference/NSString_UIKit_Additions/Reference/Reference.html

por lo que su método tableView debería d algo como

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:[UIFont fontWithName:"Helvetica" size:9] forKey: NSFontAttributeName]; 

    CGSize cell_size = [string boundingRectWithSize:CGSizeMake(300,999) 
          options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin  
          attributes:stringAttributes context:nil].size; 
if (cell_size.height > 70) 
{ 
return cell_size.height; 
} 
else 
{ 
return 70; 
} 
} 

EDIT: Esto ha sido actualizado para iOS 7

0

Acabo de escribir sobre este problema y sobre cómo finalmente resolví resolverlo. Puede leer sobre esto aquí: Dynamic UITableView Cell Height Based on Contents

Básicamente, creé una subclase UITableView que automatiza el manejo y el cálculo de la altura de celda dinámica para celdas predeterminadas y personalizadas. No es una bala de plata y probablemente deba ampliarse y ajustarse, pero lo he usado como está en varias aplicaciones con buen resultado.

Puede obtener el código aquí: https://github.com/danielsaidi/AutoSizeTableView

espero que ayude!

(... y si no lo hizo, me gustaría saber por qué no)

0

He intentado muchas soluciones, pero el que trabajaba era esto, sugerido por un amigo:

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

    int height = [StringUtils findHeightForText:yourLabel havingWidth:yourWidth andFont:[UIFont systemFontOfSize:17.0f]]; 

    height += [StringUtils findHeightForText:yourOtherLabel havingWidth:yourWidth andFont:[UIFont systemFontOfSize:14.0f]]; 

    return height + CELL_SIZE_WITHOUT_LABELS; //important to know the size of your custom cell without the height of the variable labels 
} 

clase El StringUtils.h:

#import <Foundation/Foundation.h> 

    @interface StringUtils : NSObject 

    + (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font; 

    @end 

StringUtils.Clase m:

#import "StringUtils.h" 

    @implementation StringUtils 

    + (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font { 
     CGFloat result = font.pointSize+4; 
     if (text) { 
      CGSize size; 

      CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX) 
               options:NSStringDrawingUsesLineFragmentOrigin 
              attributes:@{NSFontAttributeName:font} 
               context:nil]; 
      size = CGSizeMake(frame.size.width, frame.size.height+1); 
      result = MAX(size.height, result); //At least one row 
     } 
     return result; 
    } 

    @end 

Funcionó perfectamente para mí. Tenía una Célula personalizada con 3 imágenes con tamaños fijos, 2 etiquetas con tamaños fijos y 2 etiquetas variables. Trabajado como un encanto. Espero que funcione para usted también.

Recuerdos, Alexandre.

0

iOS 7

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section 
{ 
    NSString *text = @"Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello HelloHello HelloHello HelloHello HelloHello HelloHello Hello"; 

    CGRect rect = [text boundingRectWithSize:CGSizeMake(280.0f, CGFLOAT_MAX) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:@{ 
     NSFontAttributeName: [UIFont fontWithName:@"Hellvetica" size:14.0f] 
    } context:nil]; 

    return CGSizeMake(320.0f, ceil(rect.size.height) + 10.0f); 
} 
Cuestiones relacionadas