我试图通过覆盖 UIView 的 layerClass 类方法将 CAGradientLayer 用作 UIView 子类的根层。我为 UIButton 子类做了完全相同的事情,并且一切正常,但是对于 UIView,我没有看到渐变,我只看到默认的白色视图背景。
这是我的代码:
#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
任何人都可以阐明我的问题所在吗?