我试图通过重写 UIView 的 layerClass 类方法来使用 CAGradientLayer 作为 UIView 子类的根层。我已经为 UIButton 子类做了完全相同的事情,并且一切都完美,但是对于 UIView,我没有看到渐变,我只看到默认的白色 View 背景。
这是我的代码:
#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
任何人都可以阐明我的问题所在吗?
最佳答案
我尝试了你的代码,一开始也没有看到渐变。如果我在 View 的 awakeFromNib 方法中将 View 的背景颜色设置为clearColor,它就起作用了。
关于objective-c - CAGradientLayer 作为 UIView 的图层类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10560815/