2012-05-14 22 views
5

He intentado sizeWithFont:constrainedToSize:lineBreakMode y sizeToFit, ninguno de los cuales devuelve el resultado correcto.¿Hay alguna forma de calcular de manera confiable la altura de una UITextView?

Se supone que la propiedad contentSize devuelve la altura correcta, pero no funciona hasta que la vista de texto se muestra en la pantalla, y necesito calcular la altura antes de que la vista de texto esté visible (determina la altura de un UITableViewCell.

alguien ha encontrado ningún otro método, una vista de texto personalizado o similares, que calcula correctamente la altura de un UITextView?

EDITAR debo aclarar que yo quiero la altura ideal en base a el contenido de la vista de texto.

+1

UITextView.frame.size.height? –

+0

Eso nos da la altura de una UITextView, pero estoy buscando la altura ideal en función de su contenido. Actualizaré mi pregunta. – Quentamia

Respuesta

0

Este es el código que trabajó para mí:

+ (CGFloat)heightOfComment:(NSString *)comment { 
    UILabel *label = PrototypeCell.commentLabel; 

    // NOTE: The height of the comment should always be at least the height of 
    //  one line of text. 
    if (comment.length == 0) 
     comment = @" "; 

    return [comment sizeWithFont:label.font 
       constrainedToSize:label.frame.size 
        lineBreakMode:label.lineBreakMode].height;  
} 

La clave para hacer que el trabajo era if (comment.length == 0) comment = @" ";.

+0

Esto funciona bien para etiquetas, y lo he usado para etiquetas antes, pero no es confiable para UITextViews. – Quentamia

+0

Disculpe, no lo he intentado para UITextViews. ¿Qué problema causa? –

-2

La altura no está disponible hasta que se establece la UITextview. En iOS 6, addSubview (a un UIScrollView, por ejemplo) le dio valores de diseño (es decir, frame.size.height). En iOS 7, esto no siempre sucede, y para sizeToFit, lo mismo es cierto.

he encontrado algunas soluciones, prefiero el que hace sizeToFit, entonces layoutIfNeeded antes de leer la altura (ahora cambiado):

... 
[scrollView1 addSubview: myTextView]; 

    [myTextView sizeToFit]; //added 
    [myTextView layoutIfNeeded]; //added 

CGRect frame = myTextView.frame; 
... 

Se trata de la respuesta aceptada here, ver las notas. Mi intento de explicación aquí es en el caso de que esto no sea válido para UITextviews que se agregan a UITableViewCells en lugar de UIScrollViews (por alguna razón).

+0

no tiene sentido. – Gabox

0

Cuando las técnicas que implican sizeToFit: layouSubview y no funcionan, yo uso esto:

- (CGFloat)measureHeightOfUITextView:(UITextView *)textView 
{ 
    if ([textView respondsToSelector:@selector(snapshotViewAfterScreenUpdates:)]) 
    { 
     // This is the code for iOS 7. contentSize no longer returns the correct value, so 
     // we have to calculate it. 
     // 
     // This is partly borrowed from HPGrowingTextView, but I've replaced the 
     // magic fudge factors with the calculated values (having worked out where 
     // they came from) 

     CGRect frame = textView.bounds; 

     // Take account of the padding added around the text. 

     UIEdgeInsets textContainerInsets = textView.textContainerInset; 
     UIEdgeInsets contentInsets = textView.contentInset; 

     CGFloat leftRightPadding = textContainerInsets.left + textContainerInsets.right + textView.textContainer.lineFragmentPadding * 2 + contentInsets.left + contentInsets.right; 
     CGFloat topBottomPadding = textContainerInsets.top + textContainerInsets.bottom + contentInsets.top + contentInsets.bottom; 

     frame.size.width -= leftRightPadding; 
     frame.size.height -= topBottomPadding; 

     NSString *textToMeasure = textView.text; 
     if ([textToMeasure hasSuffix:@"\n"]) 
     { 
      textToMeasure = [NSString stringWithFormat:@"%@-", textView.text]; 
     } 

     // NSString class method: boundingRectWithSize:options:attributes:context is 
     // available only on ios7.0 sdk. 

     NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; 
     [paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping]; 

     NSDictionary *attributes = @{ NSFontAttributeName: textView.font, NSParagraphStyleAttributeName : paragraphStyle }; 

     CGRect size = [textToMeasure boundingRectWithSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT) 
                options:NSStringDrawingUsesLineFragmentOrigin 
               attributes:attributes 
                context:nil]; 

     CGFloat measuredHeight = ceilf(CGRectGetHeight(size) + topBottomPadding); 
     return measuredHeight; 
    } 
    else 
    { 
     return textView.contentSize.height; 
    } 
} 
1

IOS 7 no admite la propiedad contentSize más. Intente utilizar este

CGFloat textViewContentHeight = textView.contentSize.height; 
textViewContentHeight = ceilf([textView sizeThatFits:textView.frame.size].height + 9); 

esto solucionó mi problema.

Cuestiones relacionadas