2010-08-20 17 views

Respuesta

178
CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font 
         constrainedToSize:maximumLabelSize 
         lineBreakMode:yourLabel.lineBreakMode]; 

What is -[NSString sizeWithFont:forWidth:lineBreakMode:] good for?

esta pregunta podría tener su respuesta, que trabajó para mí.


Para 2014, edité en esta nueva versión, ¡basado en el ultra útil comentario de Norbert a continuación! Esto hace todo. Saludos

// yourLabel is your UILabel. 

float widthIs = 
[self.yourLabel.text 
    boundingRectWithSize:self.yourLabel.frame.size           
    options:NSStringDrawingUsesLineFragmentOrigin 
    attributes:@{ NSFontAttributeName:self.yourLabel.font } 
    context:nil] 
    .size.width; 

NSLog(@"the width of yourLabel is %f", widthIs); 
+41

Sólo una nota: esto está obsoleta desde iOS7. La forma preferida ahora es: '[yourString boundingRectWithSize: maximumLabelSize options: NSStringDrawingUsesLineFragmentOrigin attributes: @ {NSFontAttributeName: yourLabel.font} context: nil]; ' – Norbert

+16

También puede usar la propiedad IntrinsicContentSize. No soy mucho en Objective-C, pero debe ser algo como esto: ' self.yourLabel.intrinsicContentSize' esto le dará el tamaño del contenido de la etiqueta, por lo que sólo puede obtener el ancho de allí . – Boris

1

Aquí hay algo que se me ocurrió después de aplicar unos principios distintos SO mensajes, incluyendo enlace de Aaron:

AnnotationPin *myAnnotation = (AnnotationPin *)annotation; 

    self = [super initWithAnnotation:myAnnotation reuseIdentifier:reuseIdentifier]; 
    self.backgroundColor = [UIColor greenColor]; 
    self.frame = CGRectMake(0,0,30,30); 
    imageView = [[UIImageView alloc] initWithImage:myAnnotation.THEIMAGE]; 
    imageView.frame = CGRectMake(3,3,20,20); 
    imageView.layer.masksToBounds = NO; 
    [self addSubview:imageView]; 
    [imageView release]; 

    CGSize titleSize = [myAnnotation.THETEXT sizeWithFont:[UIFont systemFontOfSize:12]]; 
    CGRect newFrame = self.frame; 
    newFrame.size.height = titleSize.height + 12; 
    newFrame.size.width = titleSize.width + 32; 
    self.frame = newFrame; 
    self.layer.borderColor = [UIColor colorWithRed:0 green:.3 blue:0 alpha:1.0f].CGColor; 
    self.layer.borderWidth = 3.0; 

    UILabel *infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(26,5,newFrame.size.width-32,newFrame.size.height-12)]; 
    infoLabel.text = myAnnotation.title; 
    infoLabel.backgroundColor = [UIColor clearColor]; 
    infoLabel.textColor = [UIColor blackColor]; 
    infoLabel.textAlignment = UITextAlignmentCenter; 
    infoLabel.font = [UIFont systemFontOfSize:12]; 

    [self addSubview:infoLabel]; 
    [infoLabel release]; 

En este ejemplo, estoy añadiendo un pin personalizado a una clase MKAnnotation que cambia el tamaño de un UILabel de acuerdo con el tamaño del texto. También agrega una imagen en el lado izquierdo de la vista, por lo que verá que parte del código administra el espaciado adecuado para manejar la imagen y el relleno.

La clave es usar CGSize titleSize = [myAnnotation.THETEXT sizeWithFont:[UIFont systemFontOfSize:12]]; y luego redefinir las dimensiones de la vista. Puede aplicar esta lógica a cualquier vista.

Aunque la respuesta de Aaron funciona para algunos, no funcionó para mí. Esta es una explicación mucho más detallada que debes probar inmediatamente antes de ir a otro lugar si quieres una vista más dinámica con una imagen y UILabel de tamaño variable. ¡Ya hice todo el trabajo por ti!

32

La respuesta seleccionada es correcta para iOS 6 y siguientes.

En iOS 7, sizeWithFont:constrainedToSize:lineBreakMode: ha sido obsoleto. Ahora se recomienda que use boundingRectWithSize:options:attributes:context:.

CGRect expectedLabelSize = [yourString boundingRectWithSize:sizeOfRect 
                options:<NSStringDrawingOptions> 
               attributes:@{ 
                NSFontAttributeName: yourString.font 
                AnyOtherAttributes: valuesForAttributes 
               } 
                context:(NSStringDrawingContext *)]; 

Tenga en cuenta que el valor de retorno no es un CGRect un CGSize. Es de esperar que va a ser de alguna ayuda a personas que lo usan en IOS 7.

88

yourLabel.intrinsicContentSize.width para Objective-C/Swift

+3

Esto funciona demasiado bien. – Krekin

+3

¡Woot! Esta es la forma más fácil de lejos. – Echelon

+3

Funciona como un amuleto – daleijn

10

En iOS8 sizeWithFont ya no se utiliza, por favor refiérase a

CGSize yourLabelSize = [yourLabel.text sizeWithAttributes:@{NSFontAttributeName : [UIFont fontWithName:yourLabel.font size:yourLabel.fontSize]}]; 

Puede agregar todos los atributos que desee en sizeWithAttributes. Otros atributos que se pueden establecer:

- NSForegroundColorAttributeName 
- NSParagraphStyleAttributeName 
- NSBackgroundColorAttributeName 
- NSShadowAttributeName 

y así sucesivamente. Pero probablemente no necesitará los demás

42

en Swift

yourLabel.intrinsicContentSize().width 
+2

también trabajando en UIButton. –

+1

¡Excelente +1 para la respuesta más simple! – iUser

5
CGRect rect = label.frame; 
rect.size = [label.text sizeWithAttributes:@{NSFontAttributeName : [UIFont fontWithName:label.font.fontName size:label.font.pointSize]}]; 
label.frame = rect; 
+2

Esto no proporciona una respuesta a la pregunta. Para criticar o solicitar aclaraciones de un autor, deje un comentario debajo de su publicación; siempre puede comentar sus propias publicaciones, y una vez que tenga suficiente [reputación] (http://stackoverflow.com/help/whats-reputation) lo hará poder [comentar cualquier publicación] (http://stackoverflow.com/help/privileges/comment). –

+0

esta respuesta indica cómo ajustar el tamaño de la etiqueta de acuerdo con el texto. ¿Cuál es el problema en esto? –

Cuestiones relacionadas