I already have a gradient on UIView, I am having trouble inserting a new one

This is the code that I already have:

CAGradientLayer *gradient = [CAGradientLayer layer]; gradient.frame = backGradient.frame; gradient.colors = [NSArray arrayWithObjects:(id)[newGradientTop CGColor], (id)[newGradientBottom CGColor], nil]; [backGradient.layer insertSublayer:gradient atIndex:0]; 

Now I'm trying to show a new gradient using the same code block, but different colors are inserted into it. But the new gradient is not displayed, and I think that is because it will not be displayed above the existing gradient.

How can i fix this?

+4
source share
3 answers

Use this function (replacing the old gradient layer with a new one):

 #define kGradientLayerKey @"MyGradientLayer" void makeViewGradient(UIView *pView,CGColorRef clr1,CGColorRef clr2) { CAGradientLayer *gradient = [CAGradientLayer layer]; [gradient setValue:@"1" forKey:kGradientLayerKey]; gradient.frame = pView.bounds; gradient.colors = [NSArray arrayWithObjects:(id)clr1,(id)clr2,nil]; CALayer *pGradientLayer = nil; NSArray *ar = pView.layer.sublayers; for (CALayer *pLayer in ar) { if ([pLayer valueForKey:kGradientLayerKey]) { pGradientLayer = pLayer; break; } } if (!pGradientLayer) [pView.layer insertSublayer:gradient atIndex:0]; else [pView.layer replaceSublayer:pGradientLayer with:gradient]; pView.backgroundColor = nil;//free memory ! } 
+3
source

Instead of adding additional layers, track the original layer and replace it with a new one. You probably want to use -replaceSublayer:with: here.

+2
source

[backGradient.layer insertSublayer:gradient atIndex:0] inserts a new layer at the bottom of the stack under any other layers. Trying [backGradient.layer addSublayer:gradient] .

0
source

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


All Articles