ios objective-c uilabel

ios - Creando programáticamente UILabel



objective-c (8)

Sé que esto debería ser muy simple, pero he estado luchando con la creación de un UILabel programáticamente y haciendo que se comporte de la manera que me gustaría.

Todo lo que quiero es poder crear una etiqueta, establecer los atributos máximos en cuanto a altura, ancho y tamaño de fuente, y luego hacer que el texto sea más pequeño Y / O simplemente truncar el texto para acomodar cadenas largas de texto.

Digamos que quiero que mi etiqueta tenga texto que tenga un ancho máximo de 380, una altura máxima de 20 y un tamaño máximo de fuente de 12.

Así que aquí está lo que he intentado hacer para crear una etiqueta así:

UILabel *fromLabel = [[UILabel alloc]initWithFrame:CGRectMake(91, 15, 0, 0)]; fromLabel.text = [self fromSender]; fromLabel.font = [UIFont fontWithName:ProximaNovaSemibold size:12]; //custom font fromLabel.numberOfLines = 1; fromLabel.baselineAdjustment = YES; fromLabel.adjustsFontSizeToFitWidth = YES; fromLabel.adjustsLetterSpacingToFitWidth = YES; fromLabel.size = [fromLabel.text sizeWithFont:fromLabel.font constrainedToSize:CGSizeMake(380, 20) lineBreakMode:NSLineBreakByTruncatingTail]; fromLabel.minimumScaleFactor = MIN_SCALE_FACTOR; fromLabel.clipsToBounds = YES; fromLabel.backgroundColor = [UIColor clearColor]; fromLabel.textColor = [UIColor blackColor]; fromLabel.textAlignment = NSTextAlignmentLeft; [collapsedViewContainer addSubview:fromLabel];

Ok, entonces aparece la etiqueta, pero el texto es más grande que 12 y la altura siempre sale a ser 21 !? Incluso si cambio los valores de altura y tamaño de texto a tamaños extremos, este código crea una etiqueta de tamaño fijo que no se puede ajustar. Lo único que puedo hacer es reducir el ancho.

Debo tener en cuenta algo básico, pero realmente no puedo averiguar cómo obtener el resultado deseado, ni entiendo por qué me estoy comportando de la manera correcta.


Swift 3:

let label = UILabel(frame: CGRect(x:0,y: 0,width: 250,height: 50)) label.textAlignment = .center label.textColor = .white label.font = UIFont(name: "Avenir-Light", size: 15.0) label.text = "This is a Label" self.view.addSubview(label)


¿Funciona lo siguiente?

UIFont * customFont = [UIFont fontWithName:ProximaNovaSemibold size:12]; //custom font NSString * text = [self fromSender]; CGSize labelSize = [text sizeWithFont:customFont constrainedToSize:CGSizeMake(380, 20) lineBreakMode:NSLineBreakByTruncatingTail]; UILabel *fromLabel = [[UILabel alloc]initWithFrame:CGRectMake(91, 15, labelSize.width, labelSize.height)]; fromLabel.text = text; fromLabel.font = customFont; fromLabel.numberOfLines = 1; fromLabel.baselineAdjustment = UIBaselineAdjustmentAlignBaselines; // or UIBaselineAdjustmentAlignCenters, or UIBaselineAdjustmentNone fromLabel.adjustsFontSizeToFitWidth = YES; fromLabel.adjustsLetterSpacingToFitWidth = YES; fromLabel.minimumScaleFactor = 10.0f/12.0f; fromLabel.clipsToBounds = YES; fromLabel.backgroundColor = [UIColor clearColor]; fromLabel.textColor = [UIColor blackColor]; fromLabel.textAlignment = NSTextAlignmentLeft; [collapsedViewContainer addSubview:fromLabel];

editar: creo que puede encontrar un problema al utilizar adjustsFontSizeToFitWidth como minimumScaleFactor . El primero indica que también debe establecer un minimumFontWidth Ancho de minimumFontWidth (de otro modo, puede reducirse a algo bastante ilegible de acuerdo con mi prueba), pero esto se desaprueba y se reemplaza por el siguiente.

edición 2: No importa, documentación obsoleta. adjustsFontSizeToFitWidth necesita minimumScaleFactor , solo asegúrese de no pasarlo 0 como un mínimoScaleFactor (división entera, 10/12 retorno 0). Pequeño cambio en el valor de baselineAdjustment también.


Aquí es cómo crear UILabel mediante programación ..

1) Escribe esto en el archivo .h de tu proyecto.

UILabel *label;

2) Escribe esto en el archivo .m de tu proyecto.

label=[[UILabel alloc]initWithFrame:CGRectMake(10, 70, 50, 50)];//Set frame of label in your viewcontroller. [label setBackgroundColor:[UIColor lightGrayColor]];//Set background color of label. [label setText:@"Label"];//Set text in label. [label setTextColor:[UIColor blackColor]];//Set text color in label. [label setTextAlignment:NSTextAlignmentCenter];//Set text alignment in label. [label setBaselineAdjustment:UIBaselineAdjustmentAlignBaselines];//Set line adjustment. [label setLineBreakMode:NSLineBreakByCharWrapping];//Set linebreaking mode.. [label setNumberOfLines:1];//Set number of lines in label. [label.layer setCornerRadius:25.0];//Set corner radius of label to change the shape. [label.layer setBorderWidth:2.0f];//Set border width of label. [label setClipsToBounds:YES];//Set its to YES for Corner radius to work. [label.layer setBorderColor:[UIColor blackColor].CGColor];//Set Border color. [self.view addSubview:label];//Add it to the view of your choice.


Para rápido

var label = UILabel(frame: CGRect(x: 0, y: 0, width: 250, height: 50)) label.textAlignment = .left label.text = "This is a Label" self.view.addSubview(label)


In Swift - var label:UILabel = UILabel(frame: CGRectMake(0, 0, 70, 20)) label.center = CGPointMake(50, 70) label.textAlignment = NSTextAlignment.Center label.text = "message" label.textColor = UIColor.blackColor() self.view.addSubview(label)


UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 30, 300, 50)]; label.backgroundColor = [UIColor clearColor]; label.textAlignment = NSTextAlignmentCenter; label.textColor = [UIColor whiteColor]; label.numberOfLines = 0; label.lineBreakMode = UILineBreakModeWordWrap; label.text = @"Your Text"; [self.view addSubview:label];


UILabel *lbl1 = [[UILabel alloc] init]; /*important--------- */lbl1.textColor = [UIColor blackColor]; [lbl1 setFrame:position]; lbl1.backgroundColor=[UIColor clearColor]; lbl1.textColor=[UIColor whiteColor]; lbl1.userInteractionEnabled=NO; lbl1.text= @"TEST"; [self.view addSubview:lbl1];


UILabel *mycoollabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 70, 50, 50)]; mycoollabel.text=@"I am cool"; // for multiple lines,if text lenght is long use next line mycoollabel.numberOfLines=0; [self.View addSubView:mycoollabel];