setAnimationRepeatAutoreverses表现不像我预期的那样

use*_*292 5 iphone core-animation

我开始学习使用UIView动画.所以我写了以下几行:

[UIView beginAnimations:nil context:NULL];

[UIView setAnimationDuration:2.0];
[UIView setAnimationRepeatCount:2];
[UIView setAnimationRepeatAutoreverses:YES];

CGPoint position = greenView.center;
position.y = position.y + 100.0f;
position.x = position.x + 100.0f;
greenView.center = position;

[UIView commitAnimations];
Run Code Online (Sandbox Code Playgroud)

在这种情况下,UIView(一个绿色的盒子)向后移动了2次.到目前为止一切都那么好,但我发现在移动两次后,绿色框最终跳到"新位置"(position.x + 100.0f,position.y + 100.0f)而不是回到原来的位置(position.x,position.y).这使得动画看起来很奇怪(就像在setAnimationRepeatAutoreverses引起的回弹到原始位置之后,它会在最后一微秒内跳回到新的位置!)

什么是让绿箱不会在最后一分钟跳到新位置的最佳方法?

Nic*_*rge 1

我在 alpha 属性上使用 UIView 动画时遇到了完全相同的问题。最糟糕的是,动画在发送animationDidStop:委托消息之前跳转到“最终”位置,这意味着您无法在那里手动设置原始状态。

我的解决方案是使用animationDidStop委托消息创建一个新的动画块,并将它们全部串在一起:

- (void)performAnimation
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(phase1AnimationDidStop:finished:context:)];

    // Do phase 1 of your animations here
    CGPoint center = someView.center;
    center.x += 100.0;
    center.y += 100.0;
    someView.center = center;

    [UIView commitAnimations];
}

- (void)phase1AnimationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(phase2AnimationDidStop:finished:context:)];

    // Do phase 2 of your animations here
    CGPoint center = someView.center;
    center.x -= 100.0;
    center.y -= 100.0;
    someView.center = center;

    [UIView commitAnimations];
}

- (void)phase2AnimationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
    // Perform cleanup (if necessary)
}
Run Code Online (Sandbox Code Playgroud)

您可以通过这种方式将任意数量的动画块串在一起。这似乎是浪费代码,但直到苹果给我们一个 -[UIView setAnimationFinishesInOriginalState:] 属性或类似的东西,这是我发现解决这个问题的唯一方法。