2010-03-18 15 views
17

Estoy usando CAKeyframeAnimation para animar una vista a lo largo de un CGPath. Cuando termine la animación, me gustaría poder llamar a algún otro método para realizar otra acción. ¿Existe una forma correcta de hacer esto?¿Cómo especificar el selector cuando CAKeyframeAnimation finaliza?

He analizado el uso de setAnimationDidStopSelector de UIView :, sin embargo, de los documentos parece que solo se aplica cuando se usa dentro de un bloque de animación UIView (beginAnimations and commitAnimations). También lo probé por si acaso, pero parece que no funciona.

He aquí algunos ejemplos de código (esto es dentro de un método subclase UIView personalizado):

// These have no effect since they're not in a UIView Animation Block 
[UIView setAnimationDelegate:self]; 
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];  

// Set up path movement 
CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"path"]; 
pathAnimation.calculationMode = kCAAnimationPaced; 
pathAnimation.fillMode = kCAFillModeForwards; 
pathAnimation.removedOnCompletion = NO; 
pathAnimation.duration = 1.0f; 

CGMutablePathRef path = CGPathCreateMutable(); 
CGPathMoveToPoint(path, NULL, self.center.x, self.center.y); 

// add all points to the path 
for (NSValue* value in myPoints) { 
    CGPoint nextPoint = [value CGPointValue]; 
    CGPathAddLineToPoint(path, NULL, nextPoint.x, nextPoint.y); 
} 

pathAnimation.path = path; 
CGPathRelease(path); 

[self.layer addAnimation:pathAnimation forKey:@"pathAnimation"]; 

Una solución que estaba considerando que debería funcionar, pero no me parece la mejor manera, es utilizar PerformanceSelector de NSObject: withObject: afterDelay :. Mientras establezca el retraso igual a la duración de la animación, entonces debería estar bien.

¿Hay una manera mejor? ¡Gracias!

Respuesta

34

O puede incluir su animación con:

[CATransaction begin]; 
[CATransaction setCompletionBlock:^{ 
        /* what to do next */ 
       }]; 
/* your animation code */ 
[CATransaction commit]; 

Y configurar el bloque de terminación de manejar lo que tiene que hacer.

4

Swift 3 sintaxis para este answer.

CATransaction.begin() 
CATransaction.setCompletionBlock { 
    //Actions to be done after animation 
} 
//Animation Code 
CATransaction.commit() 
Cuestiones relacionadas