top guidelines bar iphone ios cocoa-touch uiview core-animation

guidelines - Mejores prácticas de animación UIView de iPhone



ios top bar (9)

Aquí está el código para la animación suave, puede ser útil para muchos desarrolladores.
Encontré 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.

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

Por ejemplo, el proyecto de ejemplo ViewTransitions de apple usa 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 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.


De la sección de referencia de UIView sobre el beginAnimations:context: :

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

Ejemplo de animación basada en bloques basada en el comentario de Tom

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


De todos modos, el método "Bloque" se prefiere ahora en días. Explicaré el bloque simple a continuación.

Considere lo recortado 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!"); }]; }

Espero que esté limpio!


En los documentos de UIView , lee sobre esta función para ios4 +

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



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 obteniendo muchos beginAnimation desde el 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.


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

El enfoque de CATransition 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 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 quisieras hacer un fundido de entrada, tendrías que profundizar en CATransition''s transición de fundido CATransition''s , o configurar una animación explícita del alfa de tu UIView .

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


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


probemos y paguemos por Swift 3 ...

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