Ios 在UITableViewCell子类中添加CAGradientLayer需要帮助吗
在UITableViewCell子类中,我试图添加渐变层,但它不起作用,我在互联网上搜索,但确实找到了对我有效的解决方案,代码如下:Ios 在UITableViewCell子类中添加CAGradientLayer需要帮助吗,ios,objective-c,uitableview,cagradientlayer,Ios,Objective C,Uitableview,Cagradientlayer,在UITableViewCell子类中,我试图添加渐变层,但它不起作用,我在互联网上搜索,但确实找到了对我有效的解决方案,代码如下: -(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if(self){
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if(self){
_gradientLayer = [CAGradientLayer layer];
_gradientLayer.frame = self.bounds;
_gradientLayer.colors = @[[UIColor whiteColor], [UIColor greenColor], [UIColor blueColor], [UIColor orangeColor]];
_gradientLayer.locations = @[@0.00f, @0.01f, @0.95f, @1.00f];
[[[[self layer] sublayers] objectAtIndex:0] removeFromSuperlayer];
self.backgroundColor = [UIColor clearColor];
[self.layer insertSublayer:_gradientLayer above:[self.layer.sublayers firstObject]];
}
return self;
}
-(void)layoutSubviews {
[super layoutSubviews];
_gradientLayer.frame = self.bounds;
}
有人能告诉我为什么它不工作,这段代码有什么问题吗?您的问题是您使用UIColor对象作为渐变层颜色,但您需要使用CGColor对象:
_gradientLayer.colors = @[(__bridge id)[UIColor whiteColor].CGColor, (__bridge id)[UIColor greenColor].CGColor, (__bridge id)[UIColor blueColor].CGColor, (__bridge id)[UIColor orangeColor].CGColor];
代码没有问题,它将层添加到单元本身。尝试将其添加到contentView或使contentView透明。正如我在问题中提到的,我使用的是UITableViewCell子类和initWithStyle do触发器,但仍然没有渐变:(。