CAGradientLayer does not work on iOS 7 (but works on iOS 6)

I use the following code to add a subtitle gradient effect to a table cell.

// add a layer that overlays the cell adding a subtle gradient effect CAGradientLayer* gradientLayer = [CAGradientLayer layer]; NSLog(@"%@",NSStringFromCGRect(cell.bounds)); gradientLayer.frame = cell.bounds; gradientLayer.colors = @[(id)[[UIColor colorWithWhite:1.0f alpha:0.2f] CGColor], (id)[[UIColor colorWithWhite:1.0f alpha:0.1f] CGColor], (id)[[UIColor clearColor] CGColor], (id)[[UIColor colorWithWhite:0.0f alpha:0.1f] CGColor]]; gradientLayer.locations = @[@0.00f, @0.01f, @0.95f, @1.00f]; [cell.layer insertSublayer:gradientLayer atIndex:0]; 

After running the code, I see that CAGradientLayer is added to my cell.layer. But I don’t see it at all when I launch the application on my iOS 7 Simulator.

 <CALayer:0xaca1980; sublayers = (<CAGradientLayer: 0xaad2110>, <CALayer: 0xaca2a70>); 

The code works on iOS 6 without problems.

If CAGradientLayer no longer works on iOS 7, what can I do to add gradients to the table cell?

Thanks in advance.

+4
source share
4 answers

I fixed this problem by changing

 [cell.layer insertSublayer:gradientLayer atIndex:0]; 

to

 [cell.layer insertSublayer:gradientLayer atIndex:1]; 

For backward compatibility. I am using code like this

  if ([Common isiOS7]) { [self.layer insertSublayer:_gradientLayer atIndex:1]; } else { [self.layer insertSublayer:_gradientLayer atIndex:0]; } 
+2
source

I fixed this by setting the background color of the cell. In this case, you can maintain the index as 0, so the elements are displayed as well as the gradient is displayed.

 cell.backgroundColor = [UIColor clearcolor]; [cell.layer insertSublayer:gradientLayer atIndex:0]; 
+4
source

As in my comment above, I am a little foggy why this works. It seems that after several tests on iOS6 I have 2 sublayers, where for iOS7 I have 1. That this is due to the introduction of indexes outside of me. I don't understand why setting the gradient to index 1 works ... doh! :)

But for my needs, I required a gradient to appear above everything else, so instead of using the answer above with OS checks (which BTW works fine !!), I did something like:

 [self.layer insertSublayer:_gradientLayer above:[self.layer.sublayers firstObject]]; 
+3
source

Update April 2016

So, I came across this question as I had a similar problem. For me, the following miraculously did the trick:

instead of gradient.colors = @[*colors*] , I had to use gradient.colors = [NSArray arrayWithObjects: *colors*, nil]

Maybe Apple’s mistake, or something that I don’t understand. Hope this helps anyone!

0
source

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


All Articles