4

To add a background gradient to a UILabel I use the following code.

Before using the gradient, UILabel Appears like this.

WithOut Gradient

Now, to add a gradient I use the following code.

   CAGradientLayer *gradLayer=[CAGradientLayer layer];
    gradLayer.frame=self.myView.layer.bounds;
    [gradLayer setColors:[NSArray arrayWithObjects:(id)([UIColor redColor].CGColor), (id)([UIColor cyanColor].CGColor),nil]];
    gradLayer.endPoint=CGPointMake(1.0, 0.0);

    [self.myView.layer addSublayer:gradLayer];

The UILabel then is as follows, but with no text.

With Gradient

I also try to add the layer at the bottom of the UILabel layer but no success.

[self.myView.layer insertSublayer:gradLayer atIndex:0];
weber67
  • 525
  • 1
  • 9
  • 18
  • Try adding the gradient to a view and then adding the label as a subview of that view. if you set the color of the label to `[UIColor clearColor]`, the gradient and the text should show. – kmikael May 11 '13 at 11:01
  • So you mean to say, one cannot set gradient to a UILabel.Then as per your say, I will have to unnecessarily add a UIView, set its gradient and then add UILabel. Nice, but introduction of a object will increase memory footprint if many UILabel are to be addded – weber67 May 11 '13 at 11:06
  • I don't think one extra plain `UIView` per `UILabel` will affect memory that much. – kmikael May 11 '13 at 11:11

1 Answers1

6

You will probably need to instead set the label on to top of a different UIView:

 UIView *labelBackground = [[UIView alloc] initWithFrame:self.label.frame];
 self.label.backgroundColor = [UIColor clearColor];
 self.label.frame = self.label.bounds;

 CAGradientLayer *gradLayer=[CAGradientLayer layer];
 gradLayer.frame = labelBackground.layer.bounds;
 [gradLayer setColors:[NSArray arrayWithObjects:(id)([UIColor redColor].CGColor), (id)([UIColor cyanColor].CGColor),nil]];
 gradLayer.endPoint=CGPointMake(1.0, 0.0);

 [labelBackground.layer addSublayer:gradLayer];

 [labelBackground addSubview:self.label];

 [self.view addSubview:labelBackground];
Undo
  • 25,519
  • 37
  • 106
  • 129