2011-03-25 9 views
52

Estoy trabajando en una aplicación, en la que estoy obligado a cambiar el tamaño del área de texto en función del texto que se mostrará.UILabel cambio automático de tamaño en función del texto que se mostrará

En primer lugar, no estoy seguro de esto tampoco debería usar UILabel (lógicamente es la mejor opción para mostrar texto estático, que es en mi caso) o UITextView.

¿Cómo deseo usarlo?
Quiero simplemente iniciar mi etiqueta o vista de texto para ese asunto con Texto. En su lugar, primero defino el marco y luego restrinjo mi texto en esa área.

Si puede sugerir la solución adecuada, será una gran ayuda.

Revisé la documentación y otras referencias, pero no encontré mucho que pudiera ayudarme aquí o podría haberlo pasado por alto.

Respuesta

95

El método sizeToFit funcionó muy bien.

Lo seguí.

UILabel *testLabel =[[UILabel alloc] initWithFrame:CGRectMake(6,3, 262,20)]; // RectMake(xPos,yPos,Max Width I want, is just a container value); 

NSString * [email protected]"this is test this is test inthis is test ininthis is test inthis is test inthis is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ..."; 

testLabel.text = test; 
testLabel.numberOfLines = 0; //will wrap text in new line 
[testLabel sizeToFit]; 

[self.view addSubview:testLabel]; 
+15

cambió el tamaño de la vista horizontalmente no verticalmente – cV2

+0

solución beriks cambia el tamaño de forma correcta correctamente – Fonix

28

puede encontrar un tamaño de texto con:

CGSize textSize = [[myObject getALongText] 
        sizeWithFont:[UIFont boldSystemFontOfSize:15] 
        constrainedToSize:CGSizeMake(maxWidth, 2000) 
        lineBreakMode:UILineBreakModeWordWrap]; 

entonces usted puede crear su UILabel así:

UILabel * lbl = [[UILabel alloc] initWithFrame:CGRectMake(0,0,textSize.width, textSize.height]; 
[lbl setNumberOfLines:0]; 
[lbl setLineBreakMode:UILineBreakModeWordWrap]; 
[lbl setText:[myObject getALongText]]; 
+2

Incorrecto: no debe preguntar al NSString qué tamaño será cuando lo dibuje dentro de un UILabel. – Berik

6

No estoy seguro de entender totalmente la cuestión, pero se puede usar el método sizeToFit en un UILabel (el método se hereda de UIView) para cambiar el tamaño de acuerdo con el texto de la etiqueta.

+0

@ user676298 marque al menos una de las respuestas como respuesta si lo ayudó. –

6

La forma más fácil de encontrar el no. de líneas dependiendo del texto. Puede usar este código:

ceil(([aText sizeWithFont:aFont].width)/self.bounds.size.width-300); 

devuelve un cierto valor flotante.

[lbl setNumberOfLines:floatvalue]; 
9

Si desea cambiar el tamaño del UILabel sólo en altura, utilice esto:

@property (nonatomic, weak) IBOutlet UILabel *titleLabel; 

CGRect titleLabelBounds = self.titleLabel.bounds; 
titleLabelBounds.size.height = CGFLOAT_MAX; 
// Change limitedToNumberOfLines to your preferred limit (0 for no limit) 
CGRect minimumTextRect = [self.titleLabel textRectForBounds:titleLabelBounds limitedToNumberOfLines:2]; 

CGFloat titleLabelHeightDelta = minimumTextRect.size.height - self.titleLabel.frame.size.height; 
CGRect titleFrame = self.titleLabel.frame; 
titleFrame.size.height += titleLabelHeightDelta; 
self.titleLabel.frame = titleFrame; 

Ahora puede utilizar titleLabelHeightDelta a la disposición de otros puntos de vista dependiendo de su tamaño de la etiqueta (sin necesidad de utilizar el diseño automático).

14

En Swift:

testLabel = UILabel(frame: CGRectMake(6, 3, 262, 20)) 
testLabel.text = test 
testLabel.numberOfLines = 0 
testLabel.sizeToFit() 

En Objective C

UILabel *testLabel = [[UILabel alloc] initWithFrame: CGRectMake(6, 3, 262, 20)]]; 
testLabel.text = test; 
testLabel.numberOfLines = 0; 
[testLabel sizeToFit]; 
2

Tenga en cuenta que con el diseño automático de llamadas sizeToFit no va a cambiar el tamaño, ya que se cambió más tarde por los cálculos de diseño automático. En este caso, debe configurar la restricción de altura adecuada para su UILabel con el valor "height> = xx".

+0

Este mensaje proporciona una respuesta a la pregunta sobre la técnica de autodiseño moderno, solo léala detenidamente. –

2

Debido a que usted va a utilizar esta solución innumerables veces en su aplicación, haga lo siguiente:

1) Crear un directorio llamado extensions y añadir un nuevo archivo llamado interior UILabel.swift con el siguiente código:

import UIKit 

extension UILabel { 
    func resizeToText() { 
     self.numberOfLines = 0 
     self.sizeToFit() 
    } 
} 

2) En el código de aplicación, definir el ancho de la etiqueta que desee y sólo llamar resizeToText():

label.frame.size.width = labelWidth 
label.resizeToText() 

Esto mantendrá el ancho mientras aumenta la altura automáticamente.

0

probado código abajo, funciona para multilínea

self.labelText.text = string; 
self.labelText.lineBreakMode = NSLineBreakByWordWrapping; 
self.labelText.numberOfLines = 0; 
0

Se puede cambiar el tamaño de la etiqueta dependiendo de la duración de la cadena por, usando esta función

func ChangeSizeOfLabel(text:String) -> CGSize{ 

    let font = UIFont(name: "HelveticaNeue", size: 12)! 
    let textAttributes = [NSFontAttributeName: font] 
    let size = text.boundingRectWithSize(CGSizeMake(310, 999), options: .UsesLineFragmentOrigin, attributes: textAttributes, context: nil) 
    let adjustSize = CGSizeMake(size.width, size.height) 
    return adjustSize 
} 

y utilizar de esta manera:

vamos

showLabel.frame = CGRectMake(x, y, width , self.ChangeSizeOfLabel("Hello , Height is changing dynamically.....").height) 
Cuestiones relacionadas