Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a CGGradient as sublayer to UILabel hides the text of label

Tags:

I want to add the gradient as a background to label. I used the following code to acheive that. but the problem is that though the gradient color appears on the label, but the text is not visible. please help

lblPatientDetail.text=PatientsDetails;  lblPatientDetail.textColor=[UIColor blackColor];    CAGradientLayer *gradient = [CAGradientLayer layer]; gradient.frame = lblPatientDetail.bounds; gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor whiteColor] CGColor],(id)[[UIColor colorWithRed:255/255.0 green:239/255.0 blue:215/255.0 alpha:1.0] CGColor],nil];    [lblPatientDetail.layer addSublayer:gradient];  lblPatientDetail.backgroundColor=[UIColor clearColor]; 
like image 390
Fatema Avatar asked Jan 31 '11 11:01

Fatema


2 Answers

Inserting a sublayer to a UILabel hides the text, so the best way to get what you want is to add the label and gradient layer to a UIView.

UIView *gradientLabelView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];  CAGradientLayer *gradient = [CAGradientLayer layer]; gradient.frame = gradientLabelView.bounds; gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor whiteColor] CGColor],(id)[[UIColor colorWithRed:255/255.0 green:239/255.0 blue:215/255.0 alpha:1.0] CGColor],nil];  [gradientLabelView.layer addSublayer:gradient];  lblPatientDetail.frame = gradientLabelView.bounds; lblPatientDetail.backgroundColor = [UIColor clearColor]; [gradientLabelView addSubview:lblPatientDetail];  [self addSubview:gradientLabelView]; 
like image 138
James P Avatar answered Nov 12 '22 11:11

James P


The suggested answer with the UILabel inside a UIView works. Apparently UILabels cannot have text within them after giving the background a gradient color background... don't know why....

But heres the full code for the solution.... hope this helps someone :)

UIView *EnvironmentalsLabelView = [[UIView alloc] initWithFrame:CGRectMake(0, 300, 320, 20)]; CAGradientLayer *gradient = [CAGradientLayer layer]; gradient.frame = EnvironmentalsLabelView.bounds; gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor darkGrayColor]CGColor], (id)[[UIColor blackColor]CGColor], nil]; [EnvironmentalsLabelView.layer insertSublayer:gradient atIndex:0]; [scroller addSubview:EnvironmentalsLabelView];  UILabel *EnviornmentalsLabelText = [[UILabel alloc] initWithFrame:EnvironmentalsLabelView.bounds]; [EnviornmentalsLabelText setFont:[UIFont fontWithName:@"Arial-BoldMT" size:12.0f]]; EnviornmentalsLabelText.textAlignment = NSTextAlignmentCenter; EnviornmentalsLabelText.backgroundColor = [UIColor clearColor]; EnviornmentalsLabelText.text = @"Environmental Benefits"; [EnvironmentalsLabelView addSubview:EnviornmentalsLabelText]; 

Happy coding!!!!

like image 20
jsetting32 Avatar answered Nov 12 '22 10:11

jsetting32