无法删除CAShapeLayer

时间:2015-09-20 19:38:14

标签: ios uiviewcontroller cashapelayer

我在屏幕上总共画了21条线作为测量工具。这些线在UIViewController.view上绘制为一个图层。我试图删除如下行。 NSLog声明证实我正在寻找我正在寻找的所有21个CAShapeLayers。

CAShapeLayer* layer = [[CAShapeLayer alloc]init];
    for (UIView *subview in viewsToRemove){
        if([subview isKindOfClass:[CAShapeLayer class]]){
            count++;
            NSLog(@"%d: %@", count, subview);
            [layerArray addObject:layer];
        }
    }
    for(CAShapeLayer *l in layerArray){
        [l removeFromSuperlayer];
    }

任何帮助删除这些行的帮助都将非常感激。

我不认为这是必要的,但如果你想看到代码在这里画线,那就是:

for(int i = 0; i < numberOfColumns; i++){
    CAShapeLayer *lineShape = nil;
    CGMutablePathRef linePath = nil;
    linePath = CGPathCreateMutable();
    lineShape = [CAShapeLayer layer];
    if(i == 0 || i == 20 || i == 10 || i == 3 || i == 17)
        lineShape.lineWidth = 4.0f;
    else
        lineShape.lineWidth = 2.0f;
    lineShape.lineCap = kCALineCapRound;
    if( i == 0 || i == 20)
        lineShape.strokeColor = [[UIColor whiteColor]CGColor];
    else if(i == 3 || i == 17)
        lineShape.strokeColor = [[UIColor redColor]CGColor];
    else if (i == 10)
        lineShape.strokeColor = [[UIColor blackColor]CGColor];
    else
        lineShape.strokeColor = [[UIColor grayColor]CGColor];

    x += xIncrement;  y = 5;


    int toY = screenHeight - self.toolBar.frame.size.height - 10;
    CGPathMoveToPoint(linePath, NULL, x, y);
    CGPathAddLineToPoint(linePath, NULL, x, toY);
    lineShape.path = linePath;
    CGPathRelease(linePath);
    [self.view.layer addSublayer:lineShape];

1 个答案:

答案 0 :(得分:1)

你的代码毫无意义:

CAShapeLayer* layer = [[CAShapeLayer alloc]init];
for (UIView *subview in viewsToRemove){
    if([subview isKindOfClass:[CAShapeLayer class]]){
        count++;
        NSLog(@"%d: %@", count, subview);
        [layerArray addObject:layer];
    }
}
for(CAShapeLayer *l in layerArray){
    [l removeFromSuperlayer];
}

您正在创建一个全新的 CAShapeLayer,然后将相同的CAShapeLayer (即您的layer对象)一遍又一遍地添加到layerArray 。它永远不会在 in 界面中,它永远不会拥有一个超级层,所以从它的超级层中删除它什么也不做。

此外,这条线毫无意义:

if([subview isKindOfClass:[CAShapeLayer class]]){

子视图永远不会成为CAShapeLayer。子视图是UIView。它不是任何一种层(虽然它一层)。

想要的内容是查找已经在界面中的CAShapeLayers。当然,一个简单的方法是在创建它时保留对每个CAShapeLayer 的引用,并将其放在界面中

[self.view.layer addSublayer:lineShape];
// now store a reference to this layer in an array that you can use later!