UILabel add GradientLayer

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

Before using the gradient, UILabel appears as follows.

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

Then UILabel looks like this, but without text.

With gradient

I am also trying to add a layer at the bottom of the UILabel layer, but have not succeeded.

[self.myView.layer insertSublayer:gradLayer atIndex:0];
+2
source share
1 answer

You will probably need to set a shortcut on top of another UIView instead:

 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];
+5
source

Source: https://habr.com/ru/post/1016088/


All Articles