ImageView 上的渐变层重用

Gradient Layer over ImageView reuse

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

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

if(!cell.gradientMask){

但是,如果我将其注释掉,颜色会起作用,但随着每次添加新层,每个单元格上的渐变都会叠加(参见

我想我需要在每次迭代时删除 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;
}

您需要在创建 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];
}