2009-03-10 9 views
139

¿Qué se considera la mejor práctica para animar las transiciones de vista en el iPhone?Mejores prácticas de UIView Animation de iPhone

Por ejemplo, el proyecto ViewTransitions muestra de Apple utiliza un código como:

CATransition *applicationLoadViewIn = [CATransition animation]; 
[applicationLoadViewIn setDuration:1]; 
[applicationLoadViewIn setType:kCATransitionReveal]; 
[applicationLoadViewIn setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]]; 
[[myview layer] addAnimation:applicationLoadViewIn forKey:kCATransitionReveal]; 

, pero también hay fragmentos de código que flotan alrededor de la red que se ven así:

[UIView beginAnimations:nil context:nil]; 
[UIView setAnimationDuration:0.75]; 
[UIView setAnimationDelegate:self]; 
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:myview cache:YES]; 
[myview removeFromSuperview]; 
[UIView commitAnimations]; 

¿Cuál es la mejor ¿enfoque? Si pudieras proporcionar un fragmento, sería muy apreciado.

NOTA: No he podido obtener el segundo enfoque para que funcione correctamente.

Respuesta

117

Desde la sección de UIView reference 's sobre el método beginAnimations:context::

El uso de este método no se recomienda en el iPhone OS 4.0 y posterior. Deberías usar los métodos de animación basados ​​en bloques en su lugar.

ejemplo de animación basada en bloques basado en comentario de Tom

[UIView transitionWithView:mysuperview 
        duration:0.75 
        options:UIViewAnimationTransitionFlipFromRight 
       animations:^{ 
        [myview removeFromSuperview]; 
       } 
       completion:nil]; 
+1

gracias por actualizar este rafael. –

+4

Entonces ... para ser claro, eso significa usar el primer enfoque (CATransición), ¿no el segundo? –

+2

Sí, es el primer enfoque (CATransition). – NebulaFox

52

La diferencia parece ser la cantidad de control que necesita sobre la animación.

El enfoque CATransition le da más control y, por lo tanto, más cosas para configurar, p. Ej. la función de tiempo Al ser un objeto, puede almacenar para más adelante, refactoriza señalar todas sus animaciones en ella para reducir código duplicado, etc.

Los métodos de clase UIView son métodos de conveniencia para animaciones comunes, pero son más limitados que CATransition. Por ejemplo, solo hay cuatro posibles tipos de transición (giro a la izquierda, giro a la derecha, curvatura, curvatura hacia abajo). Si quisiera hacer un fundido de entrada, tendría que buscar la transición de desvanecimiento CATransition's, o configurar una animación explícita del alfa de su UIView.

Tenga en cuenta que CATransition en Mac OS X le permitirá especificar un filtro de CoreImage arbitraria para su uso como una transición, pero tal como está ahora no se puede hacer esto en el iPhone, que carece de CoreImage.

+7

Tenga en cuenta que esto es iOS 2.0 consejos de la época. Vea la respuesta de Rafael Vega sobre los métodos basados ​​en bloques si tiene iOS 4.0 o superior. –

+0

También tenga en cuenta que CoreImage ya está disponible a partir de iOS 5, pero solo algunas de sus características. Creo que puede usar una transición de CoreImage en una animación, pero no puede hacer filtros CoreImage personalizados en iOS (5). –

69

He estado utilizando este último para un montón de agradables animaciones livianas. Puede usarla para fundir dos vistas, o fundir una en frente de otra, o fundirla. Puede disparar una vista sobre otra como una pancarta, puede hacer que una vista se estire o encoja ... Estoy obteniendo un montón de millas de beginAnimation/commitAnimations.

No piense que todo lo que se puede hacer es:

[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:myview cache:YES]; 

Este es un ejemplo:

[UIView beginAnimations:nil context:NULL]; { 
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; 
    [UIView setAnimationDuration:1.0]; 
    [UIView setAnimationDelegate:self]; 
    if (movingViewIn) { 
// after the animation is over, call afterAnimationProceedWithGame 
// to start the game 
     [UIView setAnimationDidStopSelector:@selector(afterAnimationProceedWithGame)]; 

//  [UIView setAnimationRepeatCount:5.0]; // don't forget you can repeat an animation 
//  [UIView setAnimationDelay:0.50]; 
//  [UIView setAnimationRepeatAutoreverses:YES]; 

     gameView.alpha = 1.0; 
     topGameView.alpha = 1.0; 
     viewrect1.origin.y = selfrect.size.height - (viewrect1.size.height); 
     viewrect2.origin.y = -20; 

     topGameView.alpha = 1.0; 
    } 
    else { 
    // call putBackStatusBar after animation to restore the state after this animation 
     [UIView setAnimationDidStopSelector:@selector(putBackStatusBar)]; 
     gameView.alpha = 0.0; 
     topGameView.alpha = 0.0; 
    } 
    [gameView setFrame:viewrect1]; 
    [topGameView setFrame:viewrect2]; 

} [UIView commitAnimations]; 

Como se puede ver, se puede jugar con alfa, marcos, e incluso los tamaños de una vista. Jugar. Puede sorprenderse con sus capacidades.

8

En los UIView documentos, tienen una lectura acerca de esta función para iOS4 +

+ (void)transitionFromView:(UIView *)fromView toView:(UIView *)toView duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options completion:(void (^)(BOOL finished))completion 
26

Podemos animar imágenes en ios 5 usando este código simple.

CGRect imageFrame = imageView.frame; 
imageFrame.origin.y = self.view.bounds.size.height; 

[UIView animateWithDuration:0.5 
    delay:1.0 
    options: UIViewAnimationCurveEaseOut 
    animations:^{ 
     imageView.frame = imageFrame; 
    } 
    completion:^(BOOL finished){ 
     NSLog(@"Done!"); 
    }]; 
+5

esto también está disponible en iOS 4 y se conoce como animación "basada en bloques". No está restringido a iOS 5 y posterior. – johnbakers

6

De todos modos, el método "Bloque" es el preferido hoy en día. Explicaré el bloque simple a continuación.

Considere los recortes a continuación. bug2 y bug 3 son imageViews. La animación siguiente describe una animación con duración de 1 segundo después de un retraso de 1 segundo. El bug3 se mueve desde su centro al centro de bug2. Una vez que se completa la animación, se registrará "¡Animación central hecha!".

-(void)centerAnimation:(id)sender 
{ 
NSLog(@"Center animation triggered!"); 
CGPoint bug2Center = bug2.center; 

[UIView animateWithDuration:1 
         delay:1.0 
        options: UIViewAnimationCurveEaseOut 
       animations:^{ 
        bug3.center = bug2Center; 
       } 
       completion:^(BOOL finished){ 
        NSLog(@"Center Animation Done!"); 
       }]; 
} 

Hope that's clean !!!

+1

asignó el bug3.center de CGPoint a bug3Center y justo después de eso asigna el bug2.center CGPoint a la misma variable bug3Center? Por qué estás haciendo eso ? – pnizzle

+0

creo que necesita verificar su código :-) – SomaMan

+0

¡oopss! eso es un tipo de amigos. Actualizado ahora – Deepukjayan

2

Aquí es el código para la animación suave, podría ser útil para muchos desarrolladores.
I found this snippet of code from this tutorial.

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"]; 
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]]; 
[animation setAutoreverses:YES]; 
[animation setFromValue:[NSNumber numberWithFloat:1.3f]]; 
[animation setToValue:[NSNumber numberWithFloat:1.f]]; 
[animation setDuration:2.f]; 
[animation setRemovedOnCompletion:NO]; 

[animation setFillMode:kCAFillModeForwards]; 
[[self.myView layer] addAnimation:animation forKey:@"scale"];/// add here any Controller that you want t put Smooth animation. 
1

vamos a lo intentan y salida para SWIFT 3 ...

UIView.transition(with: mysuperview, duration: 0.75, options:UIViewAnimationOptions.transitionFlipFromRight , animations: { 
    myview.removeFromSuperview() 
}, completion: nil)