UILabel add GradientLayer [duplicate]

2020-03-26 06:55发布

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

1条回答
我只想做你的唯一
2楼-- · 2020-03-26 07:37

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];
查看更多
登录 后发表回答