无法删除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]; 

你的代码没有意义:

 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]; } 

您正在创build一个全新的 CAShapeLayer,然后将相同的CAShapeLayer (即layer对象)反复添加到layerArray 。 它从来没有界面上,它从来没有超级层,所以从它的超级层中删除它什么都不做。

而且,这条线是毫无意义的:

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

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

想要的是寻找已经在界面中的CAShapeLayers。 当然,一个简单的方法就是在创build它时把每个CAShapeLayer的引用放到界面中

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