Nat
Nat

Reputation: 12942

CALayer - remove from view

I'm adding CAShapeLayer with some CABasicAnimation. I want to be able to remove the layer and draw it again but I can't succeed with this.

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

}

However a moment after calling [self setNeedsDisplay]; even though it stops at the breakpoint in drawLayer method, the drawing doesn't disappear and animate in again. alayer is declared as nonatomic, strong property. What am I doing wrong?

Upvotes: 0

Views: 487

Answers (2)

Wan Lutfi Wan Hatta
Wan Lutfi Wan Hatta

Reputation: 332

You should not call [self drawLayer]; fromm drawRect: because it is called periodically. Use other viewDidLoad or call it from other method instead

Edited:

drawRect: should only be used for drawing, I don't know if it will even work if you add animation from there.

If you want it to disappear and appear, you should try to add delay using [self performSelector:withObject:afterDelay:].

I think changing hidden or opacity should suffice, you only need to removeAllAnimations to make sure no more animation attached to that layer.

However I think you should try other way than calling drawLayer from drawRect: because I don't it its good practice anyway.

Upvotes: 1

user3886713
user3886713

Reputation: 16

The UIView has its own property layer by default. Please try to change a variable name to shapeLayer or another one.

Upvotes: 0

Related Questions