CALayer autoresizing on iPhone/iPad: How?

Moduspwnens picture Moduspwnens · Sep 9, 2010 · Viewed 15.1k times · Source

I'm trying to create a UIView subclass ("GradientView") that will fill itself with a gradient of various colors. I've implemented it by adding a CAGradientLayer as a sub-layer of UIView's layer.

It looked good, but when the screen was rotated, it didn't resize the gradient layer. Having no luck finding a BOOL property on the layer to toggle, I overrode layoutSubviews in the GradientView.

-(void)layoutSubviews {
    self.gradientLayer.frame = self.bounds;
}

This works, but the stuff behind the GradientView is still visible during the device rotation animation. What is the easiest way to 'autoresize' that CAGradientLayer to match its parent layer's bounds so that the animation is smooth (like for UIView autoresizing)?

Answer

l8nite picture l8nite · Nov 6, 2010

You can probably get away with defining the +layerClass method on a custom UIView...

@implementation MyGradientView
+(Class) layerClass {
    return [CAGradientLayer class];
}
@end

You can initialize the layer in your controller's viewDidLoad() (or wherever), something like...

-(void)viewDidLoad {
    [super viewDidLoad];
    [(CAGradientLayer*)[mMyGradientViewInstance layer] setColors:nil];
}