2010-02-21 49 views
43

Tengo una animación básica de hilado del iPhone. ¿Hay alguna manera de que pueda "pausar" la animación para que se mantenga la posición de la vista? Supongo que una forma de hacer esto sería hacer que la animación se "complete" en lugar de llamar "eliminar", ¿cómo lo haría?¿Hay alguna manera de pausar una CABasicAnimation?

CABasicAnimation* rotationAnimation; 
rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; 
rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2]; 
rotationAnimation.duration = 100; 
rotationAnimation.cumulative = YES; 
rotationAnimation.repeatCount = HUGE_VALF; 
rotationAnimation.removedOnCompletion = NO; 
rotationAnimation.fillMode = kCAFillModeForwards; 
[myView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"]; 

Respuesta

143

aparecido recientemente nota técnica de Apple QA1673 describe cómo pausar la animación/de la capa de hoja de vida.

pausar y reanudar las animaciones en la lista es a continuación:

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

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

Editar: IOS 10 introduce nueva API - UIViewPropertyAnimator que permite manejar animaciones más interactiva, por ejemplo, se hace fácil de hacer una pausa y reanudar la animación o 'buscar' a algún valor de progreso particular.

+0

Esto funciona bien para mí, SIN EMBARGO, cuando estoy en estado de pausa y giro mi dispositivo, pierdo toda la capacidad de interactuar con la aplicación. En realidad, no se ha bloqueado, sin embargo, parece "congelado". ¿Existe un posible conflicto con "willAnimateRotationToInterfaceOrientation"? – YoCoh

+0

@YoCoh, de hecho puede detener también las animaciones de rotación estándar para una vista, y como durante las animaciones la interacción del usuario puede deshabilitarse (probablemente ese sea el caso) y la animación estándar no termina terminas con la IU atrapada en estado desactivado. no estoy seguro de cómo solucionarlo – Vladimir

+0

http://ronnqvi.st/controlling-animation-timing/ explica cómo funciona este código –

6

Establecer el estado actual de la capa de la vista para que coincida con el estado de la presentationLayer, a continuación, retire la animación:

CALayer *pLayer = [myView.layer presentationLayer]; 
myView.layer.transform = pLayer.transform; 
[myView.layer removeAnimationForKey:@"rotationAnimation"]; 
+4

Aunque esto ahorra la posición, no sirven de punto de partida cuando vuelvo a agregar la animación a la vista, la vista se mueve un poco más lento para acomodar la distancia más corta en La misma cantidad de tiempo. ¿Hay algún otro paso que deba tomarse para poder reanudar la animación donde se quedó? – mclaughlinj

0

Se puede utilizar un temporizador o manejar el método de animación delegado:

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag 

Aquí está mi código:

// ... 
[self startAnimation]; 
// ... 

- (void)startAnimation { 
CABasicAnimation* rotationAnimation; 
rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; 
rotationAnimation.fromValue = [NSNumber numberWithFloat:0]; 
rotationAnimation.toValue = [NSNumber numberWithFloat: M_2_PI]; 
rotationAnimation.duration = 1.0; 
rotationAnimation.cumulative = YES; 
// rotationAnimation.repeatCount = 0; // <- if repeatCount set to infinite, we'll not receive the animationDidStop notification when the animation is repeating 
rotationAnimation.removedOnCompletion = NO; 
rotationAnimation.fillMode = kCAFillModeForwards; 
rotationAnimation.delegate = self; // <- hanlde the animationDidStop method 
[myView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"]; 

} 

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag { 
if (shouldContinueAnimation) // <- set a flag to start/stop the animation 
    [self startAnimation]; 
} 

esperan que los pueda ayudar.

+4

¡CUIDADO! esa no es la manera recomendada de hacerlo a menos que tenga alguna necesidad especial de hacerlo de esta manera. Imagina que tienes una animación infinita corriendo. Este método no ayudará cuando estamos pausando la animación antes de que la aplicación entre en el fondo y luego intentemos reanudarla cuando entre en primer plano. – Anshu

0

más simple

self.viewBall.layer.position = self.viewBall.layer.presentationLayer().position 
7

respuesta para SWIFT 3:

Créditos @Vladimir

Código:

func pauseAnimation(){ 
    var pausedTime = layer.convertTime(CACurrentMediaTime(), fromLayer: nil) 
    layer.speed = 0.0 
    layer.timeOffset = pausedTime 
} 

func resumeAnimation(){ 
    var pausedTime = layer.timeOffset 
    layer.speed = 1.0 
    layer.timeOffset = 0.0 
    layer.beginTime = 0.0 
    let timeSincePause = layer.convertTime(CACurrentMediaTime(), fromLayer: nil) - pausedTime 
    layer.beginTime = timeSincePause 
} 
Cuestiones relacionadas