我想通過重寫UIView的layerClass類的方法來使用CAGradientLayer作爲UIView子類的根層。我爲UIButton子類做了同樣的事情,並且它完美地工作,但是對於UIView,我沒有看到漸變,我只看到了默認的白色視圖背景。CAGradientLayer作爲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
任何人都可以擺脫在哪裏我的問題在於一些輕?
你應該設置梯度圖層的顏色在你的setter方法中的高和低顏色,而不是drawRect。還要注意'colors'屬性是隱含動畫的,所以你應該將它設置在一個CATransaction中,其中disableActions設置爲YES – jrturton