【问题标题】:CALayer - remove from viewCALayer - 从视图中移除
【发布时间】:2014-07-29 11:20:07
【问题描述】:

我正在添加CAShapeLayer 和一些CABasicAnimation。我希望能够删除图层并再次绘制它,但我无法成功。

- (void)drawRect:(CGRect)rect {
    [self drawLayer];
}

- (void)drawLayer {
    if (_alayer && _layer.superlayer) {
        [_alayer removeFromSuperlayer];
        _alayer = nil;
    }

    _alayer = [[CAShapeLayer alloc] init];
    _alayer.path = [self myPath].CGPath;
    _alayer.strokeColor = [UIColor redColor].CGColor;
    _alayer.fillColor = [UIColor clearColor].CGColor;
    _alayer.lineWidth = 2.f;
    _alayer.strokeStart = 0.f;
    _alayer.strokeEnd = 1.f;
    [self.layer addSublayer:_alayer];

    // animate
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    animation.duration = 2.f;
    animation.fromValue = @0.f;
    animation.toValue = @1.f;
    [_alayer addAnimation:animateStrokeEnd forKey:@"strokeEndAnimation"];
}

}

然而,在调用[self setNeedsDisplay]; 之后,即使它在drawLayer 方法中的断点处停止,绘图也不会消失并再次动画。 alayer 被声明为 nonatomic, strong 属性。我做错了什么?

【问题讨论】:

    标签: ios objective-c core-animation calayer caanimation


    【解决方案1】:

    你不应该调用 [self drawLayer]; fromm drawRect: 因为它是定期调用的。 改用其他 viewDidLoad 或从其他方法调用它

    已编辑:

    drawRect: 应该只用于绘图,我不知道如果你从那里添加动画它是否会起作用。

    如果你想让它消失和出现,你应该尝试使用 [self performSelector:withObject:afterDelay:] 来添加延迟。

    我认为更改 hidden 或 opacity 就足够了,您只需要 removeAllAnimations 以确保没有更多动画附加到该图层。

    但是,我认为您应该尝试从 drawRect 调用 drawLayer 以外的其他方法:因为无论如何我都不是这样的好习惯。

    【讨论】:

    • 这是预期行为。当系统需要刷新视图时,我希望用其余的东西重新绘制它(所以调用 drawRect:)。
    【解决方案2】:

    默认情况下,UIView 有自己的属性layer。请尝试将变量名称更改为 shapeLayer 或另一个。

    【讨论】:

    • 好吧,在我的代码中,它被称为不同的重构代码,因此它在 SOF 上更具可读性,但你是对的,我在这里介绍的 ivar 并不是最好的主意。无论如何,这与我的问题没有任何共同之处。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 2013-10-01
    • 1970-01-01
    • 2012-12-22
    • 2019-02-22
    • 1970-01-01
    相关资源
    最近更新 更多