UILabel add GradientLayer [duplicate]

喜你入骨 提交于 2019-12-01 07:19:33

问题


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

Before using the gradient, UILabel Appears like this.

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.

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:


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


来源:https://stackoverflow.com/questions/16496359/uilabel-add-gradientlayer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!