CABasicAnimation 在完成时停止动画 - iOS
CABasicAnimation stop animation on completion - iOS
我有一个 iOS 应用程序正在重复使用 CABasicAnimation
:
CABasicAnimation *fadeAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
fadeAnim.fromValue = [NSNumber numberWithFloat:1.0];
fadeAnim.toValue = [NSNumber numberWithFloat:0.2];
fadeAnim.duration = 1.0;
fadeAnim.autoreverses = YES;
fadeAnim.repeatCount = INFINITY;
[colourbutton.titleLabel.layer addAnimation:fadeAnim forKey:@"opacity"];
我有一个按钮,按下该按钮会停止动画。
-(IBAction)stopAnim {
[colourbutton.titleLabel.layer removeAllAnimations];
}
它工作正常,但我注意到的一件事是动画突然停止,它没有让动画完成。那么我怎样才能让它完成当前的动画然后停止呢。 (或者换句话说,我怎样才能得到它 removeAllAnimations....withAnimation
?)。
附带说明一下,我是否需要包含 CoreAnimation
框架才能正常工作。到目前为止动画是 运行 而我还没有导入 CoreAnimation
框架。
谢谢,丹。
只需添加另一个动画,然后像这样删除第一个动画:
CABasicAnimation *endAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
endAnimation.fromValue = @(((CALayer *)colourbutton.titleLabel.layer.presentationLayer).opacity);
endAnimation.toValue = @(1);
endAnimation.duration = 1.0;
[colourbutton.titleLabel.layer addAnimation:endAnimation forKey:@"end"];
[colourbutton.titleLabel.layer removeAnimationForKey:@"opacity"];
这里的关键是使用表示层来获取当前状态。不要忘记设置层的实际结束状态,因为动画将在完成时移除。
在 NKorotov 的回答中,他使用 presentationLayer
来找出您在动画中的位置。这是正确的做法。
您可以采用此解决方案,但在我看来,您还必须正确计算动画的持续时间(基于原始动画的持续时间和当前动画路径的距离)。
如果您发现 "silly" 添加新动画,您或许可以在正确的时间使用 dispatch_after
调用 removeAllAnimations
。
我有一个 iOS 应用程序正在重复使用 CABasicAnimation
:
CABasicAnimation *fadeAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
fadeAnim.fromValue = [NSNumber numberWithFloat:1.0];
fadeAnim.toValue = [NSNumber numberWithFloat:0.2];
fadeAnim.duration = 1.0;
fadeAnim.autoreverses = YES;
fadeAnim.repeatCount = INFINITY;
[colourbutton.titleLabel.layer addAnimation:fadeAnim forKey:@"opacity"];
我有一个按钮,按下该按钮会停止动画。
-(IBAction)stopAnim {
[colourbutton.titleLabel.layer removeAllAnimations];
}
它工作正常,但我注意到的一件事是动画突然停止,它没有让动画完成。那么我怎样才能让它完成当前的动画然后停止呢。 (或者换句话说,我怎样才能得到它 removeAllAnimations....withAnimation
?)。
附带说明一下,我是否需要包含 CoreAnimation
框架才能正常工作。到目前为止动画是 运行 而我还没有导入 CoreAnimation
框架。
谢谢,丹。
只需添加另一个动画,然后像这样删除第一个动画:
CABasicAnimation *endAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
endAnimation.fromValue = @(((CALayer *)colourbutton.titleLabel.layer.presentationLayer).opacity);
endAnimation.toValue = @(1);
endAnimation.duration = 1.0;
[colourbutton.titleLabel.layer addAnimation:endAnimation forKey:@"end"];
[colourbutton.titleLabel.layer removeAnimationForKey:@"opacity"];
这里的关键是使用表示层来获取当前状态。不要忘记设置层的实际结束状态,因为动画将在完成时移除。
在 NKorotov 的回答中,他使用 presentationLayer
来找出您在动画中的位置。这是正确的做法。
您可以采用此解决方案,但在我看来,您还必须正确计算动画的持续时间(基于原始动画的持续时间和当前动画路径的距离)。
如果您发现 "silly" 添加新动画,您或许可以在正确的时间使用 dispatch_after
调用 removeAllAnimations
。