I am using the code below to add a subtile gradient effect to my 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 the code ran, I can see the CAGradientLayer have been added to my cell.layer. But I can't see it at all when I run the app on my iOS 7 Simulator.
<CALayer:0xaca1980; sublayers = (<CAGradientLayer: 0xaad2110>, <CALayer: 0xaca2a70>);
The code works on iOS 6 without any problem.
If CAGradientLayer doesn't work on iOS 7 any more, what can I do to add gradients to my table cell?
Thanks in advance.
I fixed this by setting the cell background color to clear. In this case you could maintain the index as 0, so the elements are shown, and the gradient is shown too.
cell.backgroundColor = [UIColor clearcolor];
[cell.layer insertSublayer:gradientLayer atIndex:0];
As per my comment above, it is a bit foggy to me why this works. It seems that after a few tests on iOS6 I have 2 sublayers, where for iOS7 I have 1. What this has to do with the insertion of indexes is beyond me. I don't see why placing the gradient at index 1 works...doh! :)
But for my needs I required the gradient to appear above everything else, so instead of using the answer above with OS checks (which works perfectly fine BTW!!), i did something like:
[self.layer insertSublayer:_gradientLayer above:[self.layer.sublayers firstObject]];
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