Mejores prácticas de animación UIView de iPhone

votos
140

¿Qué se considera la mejor práctica para animar transiciones de vista en el iPhone?

Por ejemplo, el ViewTransitionsproyecto de ejemplo de apple usa 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 flotando 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 el mejor enfoque? Si pudieras proporcionar un fragmento, sería muy apreciado.

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

Publicado el 10/03/2009 a las 14:52
fuente por usuario
En otros idiomas...                            


9 respuestas

votos
117

A partir de la referencia UIView sección 's sobre el beginAnimations:context:método:

El uso de este método no se recomienda en el iPhone OS 4.0 y posterior. Debe utilizar los métodos de animación basadas en bloques en su lugar.

Por ejemplo, de la animación basada en bloques basado en comentario de Tom

[UIView transitionWithView:mysuperview 
                  duration:0.75
                   options:UIViewAnimationTransitionFlipFromRight
                animations:^{ 
                    [myview removeFromSuperview]; 
                } 
                completion:nil];
Respondida el 09/08/2010 a las 16:02
fuente por usuario

votos
69

He estado usando este último para muchas animaciones livianas agradables. 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 sacando mucho provecho de beginAnimation/ commitAnimations.

No pienses que todo lo que puedes hacer es:

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

Aquí hay una muestra:

[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 puede ver, puede jugar con alfa, fotogramas e incluso tamaños de una vista. Jugar. Puede sorprenderse con sus capacidades.

Respondida el 04/05/2009 a las 09:22
fuente por usuario

votos
52

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

El CATransitionenfoque le brinda más control y, por lo tanto, más elementos para configurar, p. Ej. la función de tiempo Siendo un objeto, puede almacenarlo para más adelante, refactorizar para apuntar todas sus animaciones hacia él para reducir el código duplicado, etc.

Los UIViewmétodos de clase 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 quisieras hacer un fundido de entrada, tendrías que excavar para CATransition'sdesvanecer la transición o configurar una animación explícita de tu UIViewalfa.

Tenga CATransitionen cuenta que en Mac OS X le permitirá especificar un CoreImagefiltro arbitrario para usar como una transición, pero tal como está ahora no puede hacer esto en el iPhone, que no tiene CoreImage.

Respondida el 10/03/2009 a las 16:24
fuente por usuario

votos
26

Podemos animar imágenes en iOS 5 que utiliza 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!");
    }];
Respondida el 20/01/2012 a las 10:10
fuente por usuario

votos
8

En los UIViewdocumentos, tener 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
Respondida el 11/10/2011 a las 11:19
fuente por usuario

votos
6

De todos modos el método de "bloque" es preffered hoy en día. Voy a explicar la simple bloque de abajo.

Considere la snipped a continuación. Bug2 y bichos 3 son imageViews. La animación a continuación describe una animación con 1 segundo de duración después de un retardo de 1 segundo. El Bug3 se desplaza desde su centro a centro de Bug2. Una vez que se ha completado se va a registrar la animación "Centro de Animación hecho!".

-(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!");
                 }];
}

Espero que sea limpio !!!

Respondida el 08/03/2012 a las 05:12
fuente por usuario

votos
4

He encontrado un buen tutorial en este enlace. Esperamos que esto sea útil para alguien.

UIView-animación-tutorial

Respondida el 05/10/2012 a las 08:08
fuente por usuario

votos
2

Aquí es el código para la animación suave, podría ser útil para muchos desarrolladores.
He encontrado este fragmento de código de este 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.
Respondida el 03/07/2013 a las 08:19
fuente por usuario

votos
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)
Respondida el 15/03/2017 a las 09:50
fuente por usuario

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more