I find that if I stop an on going animation and start another immediately, the new one will not work. Just show my code below.
- (void)viewDidLoad {
[super viewDidLoad];
[self showTipsAnimation:@"123"];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self showTipsAnimation:@"321"];
});
}
- (void)showTipsAnimation:(NSString *)tips
{
if (tips.length == 0) {
return;
}
if (!self.tipsLabel) {
self.tipsLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 0, 0)];
self.tipsLabel.font = [UIFont systemFontOfSize:14];
self.tipsLabel.userInteractionEnabled = NO;
self.tipsLabel.textColor = [UIColor redColor];
[self.view addSubview:self.tipsLabel];
}
[self.tipsLabel.layer removeAllAnimations];
CGFloat textWidth = [tips sizeWithAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]}].width;
self.tipsLabel.frame = CGRectMake(10, 100, textWidth, [UIFont systemFontOfSize:14].pointSize);
self.tipsLabel.text = tips;
CAKeyframeAnimation *movementAnim = [CAKeyframeAnimation animationWithKeyPath:@"position"];
movementAnim.keyTimes = @[@0, @0.25, @0.75, @1];
movementAnim.values = @[[NSValue valueWithCGPoint:CGPointMake(10 + CGRectGetWidth(self.tipsLabel.frame) * 0.5, 100 + CGRectGetHeight(self.tipsLabel.frame) / 2)],
[NSValue valueWithCGPoint:CGPointMake(10 + CGRectGetWidth(self.tipsLabel.frame) * 0.5, 90 + CGRectGetHeight(self.tipsLabel.frame) / 2)],
[NSValue valueWithCGPoint:CGPointMake(10 + CGRectGetWidth(self.tipsLabel.frame) * 0.5, 90 + CGRectGetHeight(self.tipsLabel.frame) / 2)],
[NSValue valueWithCGPoint:CGPointMake(10 + CGRectGetWidth(self.tipsLabel.frame) * 0.5, 90 + CGRectGetHeight(self.tipsLabel.frame) / 2)]];
movementAnim.duration = 2;
movementAnim.delegate = self;
[self.tipsLabel.layer addAnimation:movementAnim forKey:nil];
}
Run it, and will see the first animation will be stopped, but the second will not begin. But I also find that if I change the last line of the code to:
[self.tipsLabel.layer addAnimation:movementAnim forKey:@"1"];
then everything will be fine. So why? Is this a bug?