fit content ios cocoa-touch core-animation

ios - content - css browser compatibility



AnimaciĆ³n Fade In Fade Out (12)

Aquí hay un código con el que lucho por un tiempo.

Si inicia el fundido en la animación, el texto de la etiqueta se desvanece. Si comienzo la animación de desvanecimiento, el texto de la etiqueta se desvanece.

Cuando comienzo el método startFade , solo se muestra el desvanecimiento. ¿Cómo puedo esperar a que el método fadeIn termine visualmente antes de iniciar el método fadeOut ?

-(IBAction)startFade:(id)sender{ [self fadeIn]; [self fadeOut]; } -(IBAction)fadeIn:(id)sender{ [self fadeIn]; } -(IBAction)fadeOut:(id)sender{ [self fadeOut]; } -(void) fadeIn{ [_label setAlpha:0]; [UILabel beginAnimations:NULL context:nil]; [UILabel setAnimationDuration:2.0]; [_label setAlpha:1]; [UILabel commitAnimations]; } -(void) fadeOut{ [UILabel beginAnimations:NULL context:nil]; [UILabel setAnimationDuration:2.0]; [_label setAlpha:0]; [UILabel commitAnimations]; }


Basado en la respuesta de @holex, pero simplificado un poco (como se comentó):

- (IBAction)startFade:(id)sender { [_label setAlpha:0.f]; [UIView animateWithDuration:2.f delay:0.f options:UIViewAnimationOptionCurveEaseIn | UIViewAnimationOptionAutoreverse animations:^{ [_label setAlpha:1.f]; } completion:nil]; }


Cuando llama a los métodos fadeIn y fadeOut como lo está haciendo, el código se ejecuta instantáneamente, por lo que solo verá la animación del último método llamado. La animación basada en bloques de UIView proporciona un controlador de finalización, que parece ser exactamente lo que estás buscando. Así que su código podría ser algo como esto:

-(IBAction)startFade:(id)sender { [_label setAlpha:0.0f]; //fade in [UIView animateWithDuration:2.0f animations:^{ [_label setAlpha:1.0f]; } completion:^(BOOL finished) { //fade out [UIView animateWithDuration:2.0f animations:^{ [_label setAlpha:0.0f]; } completion:nil]; }]; }

Rápido:

@IBAction func startFade(_ sender: AnyObject) { label.alpha = 0.0 // fade in UIView.animate(withDuration: 2.0, animations: { label.alpha = 1.0 }) { (finished) in // fade out UIView.animate(withDuration: 2.0, animations: { label.alpha = 0.0 }) } }


La forma más fácil sería usar:

[UIView animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion]

y agrega la llamada fadeOut al bloque de completion . La documentación puede ayudar a responder cualquier pregunta que tenga.

Si no puede usar la versión de bloque por alguna razón, entonces deberá configurar un delegado ( [UIView setAnimationDelegate:(id)delegate] ) y un selector con ( [UIView setAnimationDidStopSelector:] ) a la que el delegado responderá. .

De nuevo, vea la documentación para más detalles.


Las animaciones fade in y fade out se pueden combinar usando UIView.animate(withDuration: animations:)

UIView.animate(withDuration: animationDuration, animations: { myView.alpha = 0.75 myView.alpha = 1.0 })


Le sugiero encarecidamente que utilice una implementación genérica para poder reutilizar el código cada vez que necesite el efecto de atenuación nuevamente.

Debes crear una extensión UIView :

UIView+Animations.h

#import <Foundation/Foundation.h> @interface UIView (Animations) - (void)fadeInWithCompletion:(void (^ __nullable)(BOOL finished))completion; - (void)fadeOutWithCompletion:(void (^ __nullable)(BOOL finished))completion;; @end

UIView+Animations.m

#import "UIView+Animations.h" @implementation UIView (Animations) - (void)fadeInWithCompletion:(void (^ __nullable)(BOOL finished))completion { [UIView animateWithDuration:2 animations:^{ [self setAlpha:1]; } completion:completion]; } - (void)fadeOutWithCompletion:(void (^ __nullable)(BOOL finished))completion { [UIView animateWithDuration:2 animations:^{ [self setAlpha:0]; } completion:completion]; } @end

Por lo tanto, solo tiene que importar el nuevo archivo a su clase o dentro de su Prefix.pch y usarlo así:

[_label fadeOutWithCompletion:^(BOOL finished) { [_label fadeInWithCompletion:nil]; }];

Tenga en cuenta que también podría usar nil como parámetro de finalización cuando no tenga nada más que hacer después de la finalización.

También recomiendo que no parametrices la duración para mantener un patrón a través de toda la aplicación.

Esta implementación se puede usar en el futuro para UIButton , UILabel , UITextField ... Bueno, cualquier clase derivada de UIView .


Mi tarea era hacer que una etiqueta se desvaneciera. Y luego desaparecer con el texto cambiado. La solución fue:

-(void)performAnimationOnHistoryButtonLabelUpdatingTextTo:(NSString *)text { [UIView animateWithDuration:0.4f animations:^{ [self.historyButtonLabel setAlpha:0.0f]; } completion:^(BOOL finished) { self.historyButtonLabel.text = text; [UIView animateWithDuration:0.4f animations:^{ [self.historyButtonLabel setAlpha:1.0f]; } completion:nil]; }]; }


Prueba esto..

// desvanecerse

-(void)fadeOut:(UIView*)viewToDissolve withDuration:(NSTimeInterval)duration andWait:(NSTimeInterval)wait { [UIView beginAnimations: @"Fade Out" context:nil]; // wait for time before begin [UIView setAnimationDelay:wait]; // druation of animation [UIView setAnimationDuration:duration]; viewToDissolve.alpha = 0.0; [UIView commitAnimations]; }

// Fundirse

-(void) fadeIn:(UIView*)viewToFadeIn withDuration:(NSTimeInterval)duration andWait:(NSTimeInterval)wait { [UIView beginAnimations: @"Fade In" context:nil]; // wait for time before begin [UIView setAnimationDelay:wait]; // druation of animation [UIView setAnimationDuration:duration]; viewToFadeIn.alpha = 1; [UIView commitAnimations]; }

// Fade in from fade out

-(void) fadeInFromFadeOut: (UIView*)viewToFadeIn withDuration:(NSTimeInterval)duration { viewToFadeIn.hidden=NO; [self fadeOut:viewToFadeIn withDuration:1 andWait:0]; [self fadeIn:viewToFadeIn withDuration:duration andWait:0]; }

// operación de botón

-(void) buttonClicked :(id)sender { NSLog(@"Button clicked"); // Each button is given a tag int tag = ((UIButton*)sender).tag; if (tag ==1) { sprite.alpha =1; [self fadeOut : sprite withDuration: 10 andWait : 1 ]; } else if (tag ==2) { sprite.alpha =0; [self fadeIn : sprite withDuration: 3 andWait : 1 ]; } else { [self fadeInFromFadeOut:sprite withDuration:10]; } }

Ver este link para descargar la muestra.

Consulte este link .

Feliz de compartir con ustedes .. :-)


Respuesta genérica: puede utilizar este método para aplicar animación a cualquier objeto UIView. Primero crea una extensión de la clase UIView. Crea un archivo swift separado y escribe el código como este

import Foundation import UIKit extension UIView { func fadeIn(){ UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: { self.alpha = 1.0 }, completion: nil) } func fadeOut(){ UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { self.alpha = 0.0 }, completion: nil) } }

Aquí el yo se refiere a cualquier vista que se refiera. Puedes usar botones, etiquetas, etc. para llamar a estos 2 métodos.

Luego, en cualquier otra clase de swift, puedes llamar a fadeIn () y fadeOut () así:

self.yourUIObject.fadeIn() self.yourUIObject.fadeOut()

Esto le da el efecto deseado de animación a cualquier objeto UIO.



que hace el trabajo por usted (la etiqueta _label es su etiqueta);

- (IBAction)startFade:(id)sender { [_label setAlpha:0.f]; [UIView animateWithDuration:2.f delay:0.f options:UIViewAnimationOptionCurveEaseIn animations:^{ [_label setAlpha:1.f]; } completion:^(BOOL finished) { [UIView animateWithDuration:2.f delay:0.f options:UIViewAnimationOptionCurveEaseInOut animations:^{ [_label setAlpha:0.f]; } completion:nil]; }]; }


Swift 4 Si necesita solo un impulso al hacer clic en el botón, use eso:

@IBAction func didPressButton(_ sender: UIButton) { self.someView.alpha = 0 UIView.animate(withDuration: 0.4, delay: 0, options: [.curveEaseInOut, .autoreverse], animations: { self.someView.alpha = 1 }, completion: { _ in self.someView.alpha = 0 }) }


labelAnimate = (UILabel*) [self.view viewWithTag:101]; btnTapMe = (UIButton*) [self.view viewWithTag:100]; [btnTapMe addTarget:self action:@selector(startAnimating:) forControlEvents:UIControlEventTouchUpInside]; ////////////// -(void) startAnimating:(UIButton*)button { [labelAnimate setAlpha:0.0]; [NSTimer scheduledTimerWithTimeInterval:1.8 target:self selector:@selector(continuousEaseInOut) userInfo:button repeats:YES]; } -(void) continuousFadeInOut { [UIView animateWithDuration:2.0 delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^{ [labelAnimate setAlpha:1.0]; } completion:^(BOOL finished) { [UIView animateWithDuration:2.0 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{ [labelAnimate setAlpha:0.0]; } completion:nil]; }]; }