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

时间:2016-07-28 05:31:22

标签: ios objective-c uicollectionview uicollectionviewcell cagradientlayer

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

这是细胞的原始顺序。这是对的 This is the original order of the cells. This is correct

当我按下另一个视图控制器然后返回时会发生这种情况 This happens when I push another view controller and then 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。

我已经尝试过所有我能想到的东西,但似乎没有任何效果!

1 个答案:

答案 0 :(得分:1)

尝试一次,

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

而不是

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

更新:

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

  

当系统要求为集合视图提供新单元格时,请从数据源对象中调用此方法。如果现有单元格可用,则此方法会出现,或者根据先前注册的类或nib文件创建新单元格。

<强> 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.