zedzhao
zedzhao

Reputation: 517

How to modify the view's CALayer

I see the code in MTAnimatedLabel

 CAGradientLayer *gradientLayer  = (CAGradientLayer *)self.layer;
gradientLayer.backgroundColor   = [super.textColor CGColor];
gradientLayer.startPoint        = CGPointMake(-self.gradientWidth, 0.);
gradientLayer.endPoint          = CGPointMake(0., 0.);
gradientLayer.colors            = [NSArray arrayWithObjects:(id)[self.textColor CGColor],(id)[self.tint CGColor], (id)[self.textColor CGColor], nil];

self is an UILabel. From the document, the layer should be readonly but I don't know why in this repo, it works.

So I try these code in my program.

 UIView *gradientView = [[UIView alloc] initWithFrame:textLayer.frame];
[self.view addSubview:gradientView];
CAGradientLayer *gradient = (CAGradientLayer*)gradientView.layer;
gradient.startPoint = CGPointMake(-0.4, 0.0);
gradient.endPoint = CGPointMake(0.0, 0.0);
gradient.colors = @[(id)[UIColor darkGrayColor].CGColor, (id)[UIColor whiteColor].CGColor, (id)[UIColor darkGrayColor].CGColor];
gradient.backgroundColor = [UIColor clearColor].CGColor;
gradient.frame = textLayer.frame

It throw an error: -[CALayer setColors:]: unrecognized selector sent to instance 0x8f8dca0

I can't understand why my code is no able to run. Hope anyone can help me.

Upvotes: 0

Views: 266

Answers (1)

sage444
sage444

Reputation: 5684

looks you missed add

+ (Class)layerClass
{
    return [CAGradientLayer class];
}

to make view layer gradient, by default this method return CALayer, that not have colors property see UIView class reference

Upvotes: 2

Related Questions