ImageView重用上的渐变层 [英] Gradient Layer over ImageView reuse
问题描述
在"cellForRowAtIndexPath"中,我具有以下代码来填充图像(异步)并应用自定义渐变
Within my 'cellForRowAtIndexPath' I have the following code to populate the image (async) and apply a custom gradient
这很好,直到我为每个单元格添加了自定义颜色.当前正在做的是回收以前的颜色,而不是应用新的颜色-这可能是由于以下行将在应用到每个单元格后跳过渐变代码的原因:
This worked fine, until I added a custom colour per cell. What it's currently doing is recycling the previous colour rather than applying a new one - this is presumably due to the following line which will skip the gradient code once applied to each cell:
if(!cell.gradientMask){
但是,如果我将其注释掉,则颜色仍然有效,但是每次添加新图层时,每个单元格上的渐变都会叠加起来(请参阅
However, if I comment this out, the colours work but the gradient on each cell will stack up as a new layer is added each time (see existing issue)
我认为我需要在每次迭代时都删除gradientLayer,这是最好的方法,还是我需要对UIImageView进行子类化?
I presume I need to remove the gradientLayer on each iteration, is that the best approach or perhaps I need to subclass the 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;
}
推荐答案
您需要在创建渐变蒙版的块外设置颜色:
You need to set the colors outside the block which creates the 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];
}
这篇关于ImageView重用上的渐变层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!