nickbona
nickbona

Reputation: 1364

CAGradientLayer as layerClass for UIView

I am trying to use CAGradientLayer as the root layer of a UIView subclass via overriding the layerClass class method of UIView. I have done the EXACT same thing for a UIButton subclass, and it all works perfectly, however for UIView, I do not see a gradient, I just see the default white view background.

Here is my code:

#import <UIKit/UIKit.h>
#import "UIView+NBStyle.h"

@interface NBStylizedView : UIView

@property (nonatomic, strong) UIColor* highColor;
@property (nonatomic, strong) UIColor* lowColor;

@end

...

#import "NBStylizedView.h"
#import <QuartzCore/QuartzCore.h>

@implementation NBStylizedView

@synthesize highColor;
@synthesize lowColor;

+ (Class) layerClass {
    return [CAGradientLayer class];
}

- (void)drawRect:(CGRect)rect {
    if (self.highColor && self.lowColor) {
        CAGradientLayer* gLayer = (CAGradientLayer*) self.layer;
        [gLayer setColors:
         [NSArray arrayWithObjects:
          (id)[self.highColor CGColor], 
          (id)[self.lowColor CGColor], nil]];
    }   
    [super drawRect:rect];
}

- (void)setHighColor:(UIColor*)color {
    highColor = color;
    [self.layer setNeedsDisplay];
}

- (void)setLowColor:(UIColor*)color {
    lowColor = color;
    [self.layer setNeedsDisplay];
}

@end

Can anyone shed some light on where my problem lies?

Upvotes: 2

Views: 3188

Answers (2)

哈哈哈哈
哈哈哈哈

Reputation: 21

Because the default opaque of the view is YES, that means, the view must draw a background before drawing the content. If you set customView.opaque = NO; after the view's initiation. As to Button, the default opaque is No, and you can see in IB the Clears Graphics Context is YES.

Upvotes: 2

rdelmar
rdelmar

Reputation: 104082

I tried your code, and saw no gradient at first either. If I set the view's background color to clearColor in the view's awakeFromNib method, it worked.

Upvotes: 2

Related Questions