如何暂停和恢复UIView动画?

时间:2010-07-09 08:32:26

标签: iphone uiviewanimation

我有一个带有几个UILabel的UIView,它们从上到下动画,反之亦然。一种Autoque让我们说:)我使用2个函数:

-(void)goUp 
-(void)goDown 

这些函数将UIView动画启动到所需位置。它们都定义了 AnimationDidStopSelector ,最后调用另一个函数。一切顺利。

当触摸屏幕时,使用touchesBegan,我想暂停当前动画并使用touchesMoved事件更改UIView的垂直位置。在touchesEnded中,我希望将动画恢复到所需的最终位置。

这样做的正确方法是什么?

托马斯

5 个答案:

答案 0 :(得分:7)

我在UIView上创建了一个类别来暂停和停止动画:

@interface UIView (AnimationsHandler)

- (void)pauseAnimations;
- (void)resumeAnimations;

@end

@implementation UIView (AnimationsHandler)
- (void)pauseAnimations
{
    CFTimeInterval paused_time = [self.layer convertTime:CACurrentMediaTime() fromLayer:nil];
    self.layer.speed = 0.0;
    self.layer.timeOffset = paused_time;
}

- (void)resumeAnimations
{
    CFTimeInterval paused_time = [self.layer timeOffset];
    self.layer.speed = 1.0f;
    self.layer.timeOffset = 0.0f;
    self.layer.beginTime = 0.0f;
    CFTimeInterval time_since_pause = [self.layer convertTime:CACurrentMediaTime() fromLayer:nil] - paused_time;
    self.layer.beginTime = time_since_pause;
}

答案 1 :(得分:4)

实际上,您仍然可以根据Vladimir在我实施后暂停UIView以及CABasicAnimations动画时暂停的问题的答案暂停UIView动画我的所有动画为CABasicaAnimations然后添加了一些UIView动画,之后我认为这些动画不会被暂停,但它们也无效。 This is the relevant link

我想暂停整个视图,因此我将self.view.layer作为要暂停的图层。但对于那些不了解CALayer的人,请传递您想要暂停的view.layer。每个UIView都有一个CALayer,因此只需传入与您相关的最高view.layer。在Thomas的情况下,基于您自己的答案,您似乎希望传入self.containerView.layer暂停。

这可行的原因是因为UIView动画只是核心动画之上的一层。至少这是我的理解。

希望这有助于未来的人们想知道如何暂停动画。

答案 2 :(得分:2)

弗拉基米尔,关于CAAnimations的问题是有道理的......但我找到了一种'暂停'的方法,所以我可以继续使用UIView动画:

CALayer *pLayer = [self.containerView.layer presentationLayer];
CGRect frameStop = pLayer.frame;
pausedX = frameStop.origin.x;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.01];
[UIView setAnimationCurve: UIViewAnimationCurveLinear];     
// set view properties

frameStop.origin.x = pausedX;
self.containerView.frame = frameStop;
[UIView commitAnimations];

我在这里做的是使用presentationLayer找出动画视图的当前x值。之后,我执行一个新的动画,覆盖原始动画。确保setAnimationBeginsFromCurrentstate:YES为此。这会取消原始动画并将动画视图放在它的目标位置(它自动执行),但是在动画过程的当前位置。

希望这对其他人也有帮助! :)

答案 3 :(得分:1)

我不确定UIView是否可以直接使用,但你绝对可以做动画视图的CALayers。有关暂停和恢复CAAnimations的信息,请参阅this question

答案 4 :(得分:0)

希望它会对你有所帮助。

- (void)goUP{
    CFTimeInterval pausedTime = [self.layer timeOffset];
    self.layer.speed = 1.0;
    self.layer.timeOffset = 0.0;
    self.layer.beginTime = 0.0;
    CFTimeInterval timeSincePause = [self.layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    self.layer.beginTime = timeSincePause;
}

- (void)goDown{
    CFTimeInterval pausedTime = [self.layer convertTime:CACurrentMediaTime() fromLayer:nil];
    self.layer.speed = 0.0;
    self.layer.timeOffset = pausedTime;
}

当您调用图层动画时,它将影响所有图层树和子模式图层的动画效果。

相关问题