I am trying to add a gradient layet to my UILabel
for some reasons the CAGradientLayer
covers my text.
Am I doing anything wrong
- (void)viewDidLoad {
[super viewDidLoad];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = CGRectMake(0, 0, myLabel.frame.size.width, myLabel.frame.size.height);
gradient.colors = myColors;
[myLabel.layer insertSublayer:gradient atIndex:0];
}
The CAGradientLayer
is covering the text of your label because the text is drawn by the content of the super layer that you explicitly covered by adding a sublayer.
Your easiest solution is to use two views. A UIView
subclass where you override +[UIView layerClass]
and return a [CAGradientLayer]
. Add a good init method to setup your gradient.
Next pup add the UILabel
as a subview of your custom gradient view.
I had the same problem. I made this method to get a reference for the shape layer and or generate it if it wasn't there. This method makes sure to throw that layer in the back so that it doesn't cover the label text layer. Just use this and you should be all good, no extra subclasses required.
- (CAShapeLayer*) getShapeLayerForObject: (UIView*) object{
CAShapeLayer *maskLayer;
int loc = -1;
for(int x = 0; x < object.layer.sublayers.count; x++){
if([[object.layer.sublayers objectAtIndex:x] isKindOfClass:[CAShapeLayer class]]){
loc = x;
break;
}
}
if(loc > -1){
maskLayer = (CAShapeLayer*) [object.layer.sublayers objectAtIndex:loc];
}else{
maskLayer = [[CAShapeLayer alloc] init];
[object.layer insertSublayer:maskLayer atIndex:0];
}
return maskLayer;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With