ImageView重用上的渐变层

时间:2015-10-19 12:26:47

标签: ios objective-c core-animation cagradientlayer

在我的'cellForRowAtIndexPath'中,我有以下代码来填充图像(异步)并应用自定义渐变

这很好,直到我为每个单元格添加了自定义颜色。它目前正在做的是回收以前的颜色,而不是应用一个新颜色 - 这可能是由于以下一行将在应用于每个单元格后跳过渐变代码:

if(!cell.gradientMask){

但是,如果我对此进行评论,颜色会起作用,但每次单元格上的渐变会叠加,因为每次都会添加一个新图层(参见existing issue

我认为我需要在每次迭代时删除gradientLayer,这是最好的方法还是我需要继承UIImageView?

if (!cell.gradientMask) {
    gradientMask = [CAGradientLayer layer];
    gradientMask.frame = cell.eventImage.layer.bounds;

    gradientMask.startPoint = CGPointMake(0.5, 0.2);
   gradientMask.endPoint = CGPointMake(0.5, 1.0);


   /* THIS COLOUR CHANGES FOR EACH CELL */
   gradientMask.colors = [NSArray arrayWithObjects:
                       (id)[[UIColor colorWithRed:0.0f green:0.0f blue:1.0f alpha:0.0f] CGColor],

                       (id)[[UIColor colorWithRed:0.0f green:0.0f blue:1.0f alpha:1.0f] CGColor],nil];
    [cell.eventImage.layer insertSublayer:gradientMask atIndex:0];
    cell.gradientMask = gradientMask;
}

1 个答案:

答案 0 :(得分:1)

您需要在块外设置颜色以创建gradientMask:

if (!cell.gradientMask) {  //Operations that need to be carried out only ONCE are put inside this block
    gradientMask = [CAGradientLayer layer];
    gradientMask.frame = cell.eventImage.layer.bounds;

    gradientMask.startPoint = CGPointMake(0.5, 0.2);
   gradientMask.endPoint = CGPointMake(0.5, 1.0);

    [cell.eventImage.layer insertSublayer:gradientMask atIndex:0];
    cell.gradientMask = gradientMask;
}

//Operations that need to be carried out again and again are outside the block
if (condition1)
{
    cell.gradientMask.colors = [NSArray arrayWithObjects:
                   (id)[[UIColor colorWithRed:0.0f green:0.0f blue:1.0f alpha:0.0f] CGColor],

                   (id)[[UIColor colorWithRed:0.0f green:0.0f blue:1.0f alpha:1.0f] CGColor],nil];
}
else
{
    cell.gradientMask.colors = [NSArray arrayWithObjects:
                   (id)[[UIColor colorWithRed:0.0f green:1.0f blue:0.0f alpha:0.0f] CGColor],

                   (id)[[UIColor colorWithRed:0.0f green:1.0f blue:0.0f alpha:1.0f] CGColor],nil];
}