【问题标题】:Can't remove CAShapeLayer from Super Layer无法从超级层中删除 CAShapeLayer
【发布时间】:2017-02-01 21:56:51
【问题描述】:

如果我无法接收测量值,我正在尝试删除我创建为 CAShapeLayer 并使用 UIBezier 路径绘制的圆圈。在我的 UIView 类的 (void)drawRect 方法中,如果找到测量值,我会创建并绘制一个圆。但是,如果没有测量值,我想摆脱圆圈。由于某种原因,我不能。

这是在 -(void)drawRect 中创建圆的代码

- (void)drawRect:(CGRect)rect {

CAShapeLayer *grayCircle = [CAShapeLayer layer];
CAShapeLayer *progressArc = [CAShapeLayer layer];
DBHelper *dbHelper = [DBHelper getSharedInstance];

if ([dbHelper getPairedDevice]==nil) {
    [grayCircle removeFromSuperlayer]; // I want to remove the grayCirle if no measurement is found AKA getPairedDevice = nil
}

....

 if (_latestMeasurement) {

...

 // Gray outer circle
    UIBezierPath *grayCirclePath=[UIBezierPath bezierPathWithArcCenter:CGPointMake(radius, radius) radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES];
    grayCircle.path = [grayCirclePath CGPath];
    grayCircle.position = CGPointMake(realBounds.origin.x, realBounds.origin.y);
    grayCircle.fillColor = [UIColor clearColor].CGColor;
    grayCircle.lineCap=kCALineCapRound;
    grayCircle.strokeColor = [UIColor grayColor].CGColor;
    grayCircle.lineWidth = 30;

    // Progress arc
    UIBezierPath *progressPath=[UIBezierPath bezierPathWithArcCenter:CGPointMake(radius, radius) radius:radius startAngle:startAngle endAngle:patientOutput clockwise:YES];
    progressArc.path = [progressPath CGPath];
    progressArc.position = CGPointMake(grayCircle.frame.origin.x, grayCircle.frame.origin.y);
    progressArc.fillColor = [UIColor clearColor].CGColor;
    progressArc.lineCap=kCALineCapRound;
    progressArc.lineWidth = 30;

[self.layer addSublayer:grayCircle];
[self.layer addSublayer:progressArc];

}

所以问题来了:以下代码行没有消除灰色圆圈:

if ([dbHelper getPairedDevice]==nil) {
    [grayCircle removeFromSuperlayer];
}

我想知道为什么会这样,我怎样才能从视图的子层中删除它?

【问题讨论】:

  • 这里发生了两件事 - getPairedDevice 肯定返回 nil 吗?
  • 绝对是的
  • 当我尝试在 if 语句中访问 grayCircle 时,它​​返回 null
  • 是的 - 可以,因为您还没有初始化它的 new 实例!

标签: ios objective-c


【解决方案1】:

每次通过drawRect 时,您都会创建一个对grayCircle 的新引用。当您移除它时 - 您移除的是新的,而不是您之前绘制的。

如果你已经拥有它,你需要先找到它,然后删除它——遍历子视图,或者在类级别维护对它的引用

【讨论】:

  • 我是否应该在我的 .h 文件中将其创建为一个属性并在整个过程中使用该属性并在必要时隐藏它?
  • 这样就行了,是的。在删除之前检查它是否不为零,并从drawRect中删除定义@
  • 它似乎根本没有出现。我只是将圆圈添加为属性,然后在我的 .m 中合成它
  • 啊@Russel 很抱歉我没有初始化它。我添加了 grayCircle = [CAShapeLayer layer] 现在它显示出来了
  • 是的,它已被删除!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多