2010-04-19 19 views
27

Un "quicky": ¿cómo puedo obtener el tamaño (ancho) de un NSString?Cómo obtener el tamaño de un NSString

Estoy tratando de ver si el ancho de una cuerda para ver si es más grande que un ancho dado de la pantalla, caso en que tengo que "cortarlo" y anexarlo con "...", obtener el comportamiento habitual de un UILabel. string.length no funcionará, ya que AAAAAAAA y iiiiii tienen la misma longitud pero diferentes tamaños (por ejemplo).

Estoy algo atrapado.

Muchas gracias.

Respuesta

38

Este es un enfoque diferente. Averigüe el tamaño mínimo del texto para que no se ajuste a más de una línea. Si se ajusta a más de una línea, puede averiguar usando la altura.

Usted puede utilizar este código:

CGSize maximumSize = CGSizeMake(300, 9999); 
NSString *myString = @"This is a long string which wraps"; 
UIFont *myFont = [UIFont fontWithName:@"Helvetica" size:14]; 
CGSize myStringSize = [myString sizeWithFont:myFont 
          constrainedToSize:maximumSize 
           lineBreakMode:self.myLabel.lineBreakMode]; 

300 es el ancho de la pantalla con un poco de espacio para los márgenes. Debe sustituir sus propios valores por fuente y tamaño, y por lineBreakMode si no está utilizando IB.

Ahora myStringSize contendrá un height que puede comparar con la altura de algo que sabe que tiene solo 1 línea de alto (con la misma fuente y tamaño). Si es más grande, necesitarás cortar el texto. Tenga en cuenta que debe agregar un ... a la cadena antes de volver a verificarla (al agregar la ... podría volver a sobrepasar el límite).

Ponga este código en un bucle para cortar el texto, luego verifique nuevamente la altura correcta.

+0

¡Muchas gracias! Su respuesta fue correcta, y el truco para agregar el "..." antes de verificar el tamaño nuevamente fue acertado. – camilo

+5

Para iOS 7 debe verificar [esta respuesta] (http://stackoverflow.com/a/18951386/3965) –

+1

está en desuso después de ios7, debe usar boundingRectWithSize: .. – 7heaven

4

Debe usar Core Graphics para medir la cadena, tal como se representa con la fuente y el tamaño especificados. Consulte las respuestas al Measuring the pixel width of a string para obtener un tutorial.

+0

La respuesta de neva hizo el truco. gracias de todos modos. – camilo

10

Utilice el siguiente método.

Objective-C

- (CGSize)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font { 
    CGSize size = CGSizeZero; 
    if (text) { 
     CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName:font } context:nil]; 
     size = CGSizeMake(frame.size.width, frame.size.height + 1); 
    } 
    return size; 
} 

Swift 3,0

func findHeight(forText text: String, havingWidth widthValue: CGFloat, andFont font: UIFont) -> CGSize { 
    var size = CGSizeZero 
    if text { 
     var frame = text.boundingRect(withSize: CGSize(width: widthValue, height: CGFLOAT_MAX), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) 
     size = CGSize(width: frame.size.width, height: frame.size.height + 1) 
    } 
    return size 
} 
+0

¿Por qué altura + 1? –

+0

'size = CGSize (ancho: ceilf (frame.width), height: ceilf (frame.height))' es mejor. –

+0

La pregunta es cómo obtener el ancho de la cadena.Esta respuesta es cómo obtener la altura de la cadena si ya conoce su ancho ... buena información, pero no una respuesta a la pregunta. Creo que un mejor enfoque para hacer esta respuesta es hacer la pregunta correcta y luego responderla usted mismo, seguido con un posible comentario a esta pregunta que lo señala a la pregunta relacionada. – mah

2
sizeWithFont:constrainedToSize:lineBreakMode 

está en desuso ahora. Utilice el siguiente fragmento de código,

UIFont *font=[UIFont fontWithName:@"Arial" size:16.f]; 

NSString *name = @"APPLE"; 

CGSize size = [name sizeWithAttributes:@{NSFontAttributeName:font}]; 
Cuestiones relacionadas