Cómo calcular el ancho de UILabel basado en la longitud del texto?


Quiero mostrar una imagen junto a una UILabel, sin embargo UILabel tiene una longitud de texto variable, por lo que no se donde colocar la imagen. ¿Cómo puedo lograr esto?

Author: Jakub Truhlář, 2010-08-20

8 answers

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

¿Para qué sirve - [NSString sizeWithFont:forWidth:lineBreakMode:]?

Esta pregunta podría tener su respuesta, funcionó para mí.


Para 2014, edité en esta nueva versión, basada en el comentario ultra práctico de Norbert a continuación! Esto lo hace todo. Salud

// 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);
 183
Author: Aaron Saunders,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:25

yourLabel.intrinsicContentSize.width for Objective-C / Swift

 109
Author: Jakub Truhlář,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-18 18:19:02

En swift

 yourLabel.intrinsicContentSize().width 
 43
Author: Arshad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-20 09:37:57

La respuesta seleccionada es correcta para iOS 6 y versiones posteriores.

En iOS 7, sizeWithFont:constrainedToSize:lineBreakMode: ha sido obsoleto. Ahora se recomienda usar 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 devuelto es un CGRect no un CGSize. Esperemos que sea de alguna ayuda para las personas que lo usan en iOS 7.

 32
Author: Chetan Shenoy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-24 16:45:05

En iOS8 sizeWithFont ha sido obsoleto, consulte

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 puede establecer:

- NSForegroundColorAttributeName
- NSParagraphStyleAttributeName
- NSBackgroundColorAttributeName
- NSShadowAttributeName

Y así sucesivamente. Pero probablemente no necesitarás a los otros

 10
Author: jarora,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-31 16:51:51
CGRect rect = label.frame;
rect.size = [label.text sizeWithAttributes:@{NSFontAttributeName : [UIFont fontWithName:label.font.fontName size:label.font.pointSize]}];
label.frame = rect;
 6
Author: Honey Lakhani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-07 09:19:36

Respuesta Swift 4 que están usando Restricción

label.text = "Hello World"

var rect: CGRect = label.frame //get frame of label
rect.size = (label.text?.size(attributes: [NSFontAttributeName: UIFont(name: label.font.fontName , size: label.font.pointSize)!]))! //Calculate as per label font
labelWidth.constant = rect.width // set width to Constraint outlet
 2
Author: iOS Lifee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-30 11:09:45

Aquí hay algo que se me ocurrió después de aplicar algunos principios otros artículos de SO, incluido el enlace de Aaron's:

    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 agregando un pin personalizado a una clase MKAnnotation que redimensiona una etiqueta UILabel de acuerdo con el tamaño del texto. También agrega una imagen en el lado izquierdo de la vista, para que vea parte del código administrando 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 Aarón funciona para algunos, no funcionó para mí. Esta es una explicación mucho más detallada que debe probar inmediatamente antes de ir a cualquier otro lugar si desea una vista más dinámica con una imagen y UILabel redimensionable. ¡Ya hice todo el trabajo por ti!!

 1
Author: whyoz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-21 16:00:26