Search code examples
ioscalayerios7

CAGradientLayer is not working on iOS 7 (But working on iOS 6)


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.


Solution

  • I have fixed this issue by changing

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

    to

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

    For backward compatibility. I am using the code like this

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