Remove imageView sublayer from TableViewCell

前端 未结 1 655
臣服心动
臣服心动 2021-02-04 17:14

When I have an image I insert sublayer with CAGradientLayer,

...
layer.name = @\"Gradient\";
[cell.imageView.layer insertSublayer:layer atIndex:0];
相关标签:
1条回答
  • 2021-02-04 18:13

    The exception is thrown because you are changing the contents of the sublayers array while enumerating it with foreach loop. This is not something special to layers, a similar exception is thrown when you add/remove objects while enumerating any NSMutableArray.

    You have various options to solve this issue

    Solution 1: Stop enumerating as soon as you modify the array.

    for (CALayer *layer in cell.imageView.layer.sublayers) {
        if ([layer.name isEqualToString:@"Gradient"]) {
            [layer removeFromSuperlayer];
            break;
        }
    }
    

    Solution 2: Do not enumerate the real array, instead use its copy.

    NSArray* sublayers = [NSArray arrayWithArray:cell.imageView.layer.sublayers];
    for (CALayer *layer in sublayers) {
        if ([layer.name isEqualToString:@"Gradient"]) {
            [layer removeFromSuperlayer];
        }
    }
    

    Solution 3: Use key value coding to keep a reference to the gradient layer.

    Set it after inserting:

    [cell.imageView.layer insertSublayer:layer atIndex:0];
    [cell.imageView.layer setValue:layer forKey:@"GradientLayer"];
    

    Retrieve and remove it

    CALayer* layer = [cell.imageView.layer valueForKey:@"GradientLayer"];
    [layer removeFromSuperlayer];
    [cell.imageView.layer setValue:nil forKey:@"GradientLayer"];
    
    0 讨论(0)
提交回复
热议问题