ios 移除动画

作者: 老魏313 | 来源:发表于2017-08-30 12:45 被阅读0次

    在移除动画之前, 首先得在 layer 上添加两个动画
    示例代码:

    CABasicAnimation *animation = [CABasicAnimation animation];
    animation.keyPath = @"transform.rotation";
    animation.duration = 2.0;
    animation.byValue = @(M_PI * 2);
    animation.delegate = self;
    
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    [self.layer addAnimation:animation forKey:@"rotateAnimation"];
    
    CABasicAnimation *animation2 = [CABasicAnimation animation];
    animation2.keyPath = @"transform.scale";
    animation2.duration = 2.0;
    animation2.toValue = @2.0;
    animation2.delegate = self;
    
    animation2.removedOnCompletion = NO;
    animation2.fillMode = kCAFillModeForwards;
    [self.layer addAnimation:animation2 forKey:@"scale"];
    

    添加两个按钮来控制动画的 开始 和 移除 操作, 代码(略)

    点击开始, 执行上面的代码

    点击结束:
    1.移除制定动画

    [self.layer removeAnimationForKey:@"rotateAnimation"];
    

    2.移除所有动画

    [self.layer removeAllAnimations];
    

    查看动画结束时的打印:

    #pragma mark Animation delegate
    - (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
        NSString *strAnimation = nil;
        if ([self.layer animationForKey:@"rotateAnimation"] == anim) {
            strAnimation = @"rotateAnimation";
        }
        if ([self.layer animationForKey:@"scale"] == anim){
            strAnimation = @"scaleAnimation";
        }
        NSLog(@"%@ stop finish: %@",strAnimation, flag? @"yes": @"no");
    }
    

    特别注意:
    1.以上方法取值时 使用的是 animationForKey 而不是 valueForKey
    2.一定要把 animation 的 removedOnCompletion 设置成 NO, 否则取不到值

    执行以上代码后, 发现手动结束动画时, 图像会还原到原来的位置.
    解决方法:
    在移除动画操作后添加以下代码

    // 动画移除后 保持在当前位置
    self.layer.transform = self.layer.presentationLayer.transform;
    

    执行之后效果如下:

    效果图.gif

    相关文章

      网友评论

        本文标题:ios 移除动画

        本文链接:https://www.haomeiwen.com/subject/lmwzdxtx.html