Programmatically Creating UILabel Programmatically Creating UILabel ios ios

Programmatically Creating UILabel


Does the following work ?

UIFont * customFont = [UIFont fontWithName:ProximaNovaSemibold size:12]; //custom fontNSString * 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 UIBaselineAdjustmentNonefromLabel.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];

edit : I believe you may encounter a problem using both adjustsFontSizeToFitWidth and minimumScaleFactor. The former states that you also needs to set a minimumFontWidth (otherwhise it may shrink to something quite unreadable according to my test), but this is deprecated and replaced by the later.

edit 2 : Nevermind, outdated documentation. adjustsFontSizeToFitWidth needs minimumScaleFactor, just be sure no to pass it 0 as a minimumScaleFactor (integer division, 10/12 return 0).Small change on the baselineAdjustment value too.


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];


here is how to create UILabel Programmatically..

1) Write this in .h file of your project.

UILabel *label;

2) Write this in .m file of your project.

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.