UILabel-etiqueta de tamaño automático para ajustar el texto?


¿Es posible redimensionar automáticamente el cuadro/límites de UILabel para que se ajuste al texto contenido? (No me importa si termina más grande que la pantalla)

Entonces, si un usuario ingresa "hola" o "mi nombre es realmente largo, quiero que quepa en esta caja", nunca se trunca y la etiqueta se 'ensancha' en consecuencia?

Author: Suragch, 2012-01-10

14 answers

Por favor, echa un vistazo a mi esencia donde he hecho una categoría para UILabel para algo muy similar, mi categoría permite a un UILabel estirar su altura para mostrar todo el contenido: https://gist.github.com/1005520

O echa un vistazo a esta publicación: https://stackoverflow.com/a/7242981/662605

Esto estiraría la altura, pero puedes cambiarla fácilmente para trabajar al revés y estirar la anchura con algo como esto, que es lo que creo que quieres do:

@implementation UILabel (dynamicSizeMeWidth)

- (void)resizeToStretch{
    float width = [self expectedWidth];
    CGRect newFrame = [self frame];
    newFrame.size.width = width;
    [self setFrame:newFrame];
}

- (float)expectedWidth{
    [self setNumberOfLines:1];

    CGSize maximumLabelSize = CGSizeMake(CGRectGetWidth(self.bounds), CGFLOAT_MAX);

    CGSize expectedLabelSize = [[self text] sizeWithFont:[self font] 
                                            constrainedToSize:maximumLabelSize
                                            lineBreakMode:[self lineBreakMode]]; 
    return expectedLabelSize.width;
}

@end

Podría simplemente usar el método sizeToFit disponible en la clase UIView, pero establecer el número de líneas en 1 para ser seguro.


Actualización de IOS 6

Si está utilizando AutoLayout, entonces tiene una solución incorporada. Al establecer el número de líneas en 0, el marco cambiará el tamaño de la etiqueta adecuadamente (agregando más altura) para que se ajuste a su texto.


Actualización de IOS 8

sizeWithFont: está en desuso así que usa sizeWithAttributes: en su lugar:

- (float)expectedWidth{
    [self setNumberOfLines:1];

    CGSize expectedLabelSize = [[self text] sizeWithAttributes:@{NSFontAttributeName:self.font}];

    return expectedLabelSize.width;
}
 96
Author: Daniel,
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-07-11 11:30:25

Usando [label sizeToFit]; obtendrá el mismo resultado de la categoría Daniels.

Aunque recomiendo usar autolayout y dejar que la etiqueta cambie de tamaño en función de las restricciones.

 69
Author: Guilherme Torres Castro,
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
2016-06-28 17:40:53

Si queremos que UILabel se reduzca y expanda según el tamaño del texto, entonces storyboard with autolayout es la mejor opción. A continuación se presentan los pasos para lograr esto

Pasos

  1. Coloque UILabel en view controller y colóquelo donde quiera. También ponga 0 para numberOfLines propiedad de UILabel.

  2. Dale restricción de pin de espacio superior, Inicial y Final.

introduzca la descripción de la imagen aquí

  1. Ahora se dará una advertencia, Haga clic en el amarillo flecha.

introduzca la descripción de la imagen aquí

  1. haga Clic en Update Frame y haga clic en Fix Misplacement. Ahora esta etiqueta UILabel se reducirá si el texto es menor y se expandirá si el texto es más.
 29
Author: Yogesh Suthar,
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-06-10 11:38:49

Esto no es tan complicado como algunas de las otras respuestas lo hacen.

introduzca la descripción de la imagen aquí

Pin los bordes izquierdo y superior

Simplemente use diseño automático para agregar restricciones para fijar los lados izquierdo y superior de la etiqueta.

introduzca la descripción de la imagen aquí

Después de eso se redimensionará automáticamente.

Notas

  • No agregue restricciones para el ancho y la altura. Las etiquetas tienen un tamaño intrínseco basado en su contenido de texto.
  • Gracias a esta respuesta para ayudar con esto.
  • No es necesario establecer sizeToFit cuando se utiliza el diseño automático. Mi código completo para el proyecto de ejemplo está aquí:

    import UIKit
    class ViewController: UIViewController {
    
        @IBOutlet weak var myLabel: UILabel!
    
        @IBAction func changeTextButtonTapped(sender: UIButton) {
            myLabel.text = "my name is really long i want it to fit in this box"
        }
    }
    
  • Si desea que su etiqueta se ajuste a la línea, establezca el número de líneas en 0 en IB y agregue myLabel.preferredMaxLayoutWidth = 150 // or whatever en el código. (También fijé mi botón en la parte inferior de la etiqueta para que se moviera hacia abajo cuando aumentara la altura de la etiqueta.)

introduzca la descripción de la imagen aquí

  • Si está buscando etiquetas de tamaño dinámico dentro de un UITableViewCellentonces vea esta respuesta.

introduzca la descripción de la imagen aquí

 19
Author: Suragch,
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:03:02

Use [label sizeToFit]; para ajustar el texto en UILabel

 9
Author: Gaurav Gilani,
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
2014-07-21 08:18:20

He creado algunos métodos basados en la respuesta de Daniel anterior.

-(CGFloat)heightForLabel:(UILabel *)label withText:(NSString *)text
{
    CGSize maximumLabelSize     = CGSizeMake(290, FLT_MAX);

    CGSize expectedLabelSize    = [text sizeWithFont:label.font
                                constrainedToSize:maximumLabelSize
                                    lineBreakMode:label.lineBreakMode];

    return expectedLabelSize.height;
}

-(void)resizeHeightToFitForLabel:(UILabel *)label
{
    CGRect newFrame         = label.frame;
    newFrame.size.height    = [self heightForLabel:label withText:label.text];
    label.frame             = newFrame;
}

-(void)resizeHeightToFitForLabel:(UILabel *)label withText:(NSString *)text
{
    label.text              = text;
    [self resizeHeightToFitForLabel:label];
}
 5
Author: Doug Baker,
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-01-26 16:28:21
@implementation UILabel (UILabel_Auto)

- (void)adjustHeight {

    if (self.text == nil) {
        self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.bounds.size.width, 0);
        return;
    }

    CGSize aSize = self.bounds.size;
    CGSize tmpSize = CGRectInfinite.size;
    tmpSize.width = aSize.width;

    tmpSize = [self.text sizeWithFont:self.font constrainedToSize:tmpSize];

    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, aSize.width, tmpSize.height);
}

@end

Este es el método category. Primero debe establecer texto, luego llamar a este método para ajustar la altura de UILabel.

 3
Author: Kaijay Lu,
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-01-10 02:02:07

Puede ajustar el tamaño de su etiqueta de acuerdo con el texto y otros controles relacionados utilizando dos formas:

  1. Para iOS 7.0 y superior

    CGSize labelTextSize = [labelText boundingRectWithSize:CGSizeMake(labelsWidth, MAXFLOAT)
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:@{
                                                        NSFontAttributeName : labelFont
                                                        }
                                              context:nil].size;
    

Antes de iOS 7.0, esto se podía usar para calcular el tamaño de la etiqueta

CGSize labelTextSize = [label.text sizeWithFont:label.font 
                            constrainedToSize:CGSizeMake(label.frame.size.width, MAXFLOAT)  
                                lineBreakMode:NSLineBreakByWordWrapping];

/ / replantear otros controles basados en labelTextHeight

CGFloat labelTextHeight = labelTextSize.height;
  1. Si no desea calcular el tamaño del texto de la etiqueta, puede usar-sizeToFit en la instancia de UILabel como -

    [label setNumberOfLines:0]; // for multiline label
    [label setText:@"label text to set"];
    [label sizeToFit];// call this to fit size of the label according to text
    

/ / después de esto puedes obtener el marco de la etiqueta para replantear otros controles relacionados

 2
Author: vijeesh,
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-06-10 11:38:10
  1. Agregue restricciones faltantes en storyboard.
  2. Seleccione UILabel en storyboard y establezca los atributos "Line" en 0.
  3. Ref Toma la etiqueta UILabel al Controlador.h con id: label
  4. Controlador.m y añadir [label sizeToFit]; en viewDidLoad
 2
Author: user2941395,
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-11 05:55:42

Tuve grandes problemas con el diseño automático. Tenemos dos contenedores dentro de la celda de la mesa. El segundo contenedor se redimensiona dependiendo de la descripción del elemento (0-1000 caracteres), y la fila debe redimensionarse en función de ellos.

El ingrediente que faltaba era la restricción inferior para la descripción.

He cambiado la restricción inferior del elemento dinámico de = 0 to >= 0.

 1
Author: Bojan Tadic,
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
2016-04-21 14:55:06

Esto es lo que estoy encontrando funciona para mi situación:

1) La altura de la etiqueta UILabel tiene una restricción >= 0 usando autolayout. El ancho es fijo. 2) Asignar el texto a la etiqueta UILabel, que ya tiene una vista superior en ese punto(no estoy seguro de lo vital que es). 3) Entonces, hacer:

    label.sizeToFit()
    label.layoutIfNeeded()

La altura de la etiqueta ahora se establece apropiadamente.

 1
Author: Chris Prince,
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-04-28 02:29:09

Encaja cada vez! :)

    name.text = @"Hi this the text I want to fit to"
    UIFont * font = 14.0f;
    CGSize size = [name.text sizeWithAttributes:@{NSFontAttributeName: font}];
    nameOfAssessment.frame = CGRectMake(400, 0, size.width, 44);
    nameOfAssessment.font = [UIFont systemFontOfSize:font];
 0
Author: Hannah Louisa Carney,
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
2016-05-17 14:10:02

Puede mostrar la salida de una línea y luego establecer la propiedad Line = 0 y mostrar la salida de varias líneas y luego establecer la propiedad Line = 1 y más

[self.yourLableName sizeToFit];
 0
Author: Dixit Akabari,
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-01-06 06:29:42

También existe este enfoque:

[self.myLabel changeTextWithAutoHeight:self.myStringToAssignToLabel width:180.0f];
 -1
Author: Dave Cole,
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-06-10 11:37:16