需要帮助在UITableViewCell子类中添加CAGradientLayer

时间:2014-12-06 11:22:47

标签: ios objective-c uitableview cagradientlayer

在UITableViewCell子类中,我正在尝试添加渐变层,但它无法正常工作,我在互联网上搜索但确实找到了适合我的解决方案,这里是代码:

-(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;
}

任何人都可以告诉我为什么它不起作用,这个代码有什么问题?

1 个答案:

答案 0 :(得分:0)

您的问题是您使用UIColor对象作为渐变图层颜色,但您需要使用CGColor对象:

_gradientLayer.colors = @[(__bridge id)[UIColor whiteColor].CGColor, (__bridge id)[UIColor greenColor].CGColor, (__bridge id)[UIColor blueColor].CGColor, (__bridge id)[UIColor orangeColor].CGColor];
相关问题