UICollectionViewCell 奇怪的行为。单元格未正确更新图层

UICollectionViewCell strange behaviour. Cells not updating layer correctly

我有一个包含多个单元格的 UICollectionView,我在上面添加了一个 CAGradient 层来表示每个单元格的颜色。问题是,当我将另一个视图控制器推到当前视图控制器之上,然后弹出第二个视图控制器时,我的集合视图单元格以随机顺序改变颜色。为了给你一个想法,我附上了截图。

这是单元格的原始顺序。这是对的

当我按下另一个视图控制器然后 return 时会发生这种情况 你可以看到即使我什么都没改变,细胞的颜色也发生了变化。

这是我用来初始化单元格的代码。

[collectionview reloadData] 在 -viewWillAppear 中调用,因此每次出现视图时都会加载单元格

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self filterRecords];
    MyCell *cell = (MyCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"ProspectCVCell" forIndexPath:indexPath];


    for (int i = 0; i < [eventsSortedForAddedDate count]; i++)
    {
        Events* event = (Events*)[eventsSortedForAddedDate objectAtIndex:i];

        if ([event.activityLevel.activityName isEqualToString:@"None"])
            continue;

        color = [[event activityLevel] color];

        if (![color isEqualToString:@"#FFCCCCCC"])
            break;
        else
            color = nil;
    }


    if (!([color length] > 0) || color == nil)
    {
        color = @"#FFCCCCCC";
    }

    UIColor* myColor = [self getUIColorObjectFromHexString:color alpha:.9];

    //cell.backgroundColor = myColor;

    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = cell.bounds;
    gradient.colors = [NSArray arrayWithObjects:(id)[myColor CGColor], (id)[[UIColor whiteColor] CGColor], nil];
    gradient.locations = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0f], [NSNumber numberWithFloat:0.85f],  nil];
    //[cell.layer insertSublayer:gradient atIndex:0];
    [cell.layer insertSublayer:gradient atIndex:0];


    cell.prospectImageView.layer.shadowColor = [UIColor blackColor].CGColor;
    cell.prospectImageView.layer.shadowOffset = CGSizeMake(0, 3.0);
    cell.prospectImageView.layer.shadowRadius = 3.0;
    cell.prospectImageView.layer.shadowOpacity = 0.8;

    cell.cellLabel.text = p.displayName;

    cell.layer.borderWidth = 0.5f;
    cell.layer.borderColor = [UIColor whiteColor].CGColor;

    return cell;
}

我的取色方式没有问题,调试了多次,确认取色正确。 如果我这样做

cell.backgroundColor = myColor;

细胞没有按预期改变颜色和功能。所以我很确定问题出在 CAGradientLayer 上。

我已经尝试了所有我能想到的方法,但似乎没有任何效果!

试试这个,

 [cell.layer insertSublayer:gradient atIndex:[[cell.layer sublayers] indexOfObject:[[cell.layer sublayers] lastObject]]];

而不是

 [cell.layer insertSublayer:gradient atIndex:0];

更新:

正如评论中所问,Apple doc 说明了 dequeueReusableCellWithReuseIdentifier

Call this method from your data source object when asked to provide a new cell for the collection view. This method dequeues an existing cell if one is available or creates a new one based on the class or nib file you previously registered.

And second thing you can also remove previous layers and then can add new one at index 0. it is better because it not increase number of layer which is not necessary.