2014-12-06 24 views
0

在UITableViewCell的子類,我想添加漸變層,但它不工作,我搜索互聯網上,但沒有找到解決方案,爲我在這裏工作是代碼:需要援助的UITableViewCell子類中添加CAGradientLayer

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

能有人告訴我爲什麼它不工作,這個代碼有什麼問題?

+0

沒有什麼不對您的代碼,將其添加到細胞本身的層。嘗試將其添加到contentView或使contentView透明。 – Sandeep 2014-12-06 12:12:10

回答

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]; 
+0

正如我在我的問題中提到,我使用UITableViewCell子類和initWithStyle做觸發器,但仍然沒有梯度:(。 – 2014-12-07 19:44:19

+0

@ S.J我重新檢查您的代碼並更新了我的答案 – 2014-12-07 22:42:37