Fade In Fade Out Animación


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 fade out el texto de la etiqueta se desvanece.

Cuando comienzo el método startFade, solo se muestra fade out. Cómo puedo esperar a que el método fadeIn termine visualmente antes de comenzar 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];
}
Author: ROMANIA_engineer, 2014-01-03

12 answers

Cuando llamas a los métodos fadeIn y fadeOut de forma consecutiva como lo estás haciendo, el código se ejecuta instantáneamente, por lo que solo verás animación del último método llamado. UIView block based animation proporciona un controlador de finalización, que parece ser exactamente lo que estás buscando. Así que su código podría verse 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];

    }];
}

Swift:

@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
        })
    }
}
 105
Author: hgwhittle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-16 19:05:34

Que hace el trabajo por ti (el _label es tu 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];
    }];
}
 32
Author: holex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-02 21:06:11

Prueba esto..

/ / Fade Out

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

/ / Fundido En

-(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 del 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];
}
}

Vea este enlace para descargar la muestra..

Consulte este enlace.

Feliz de compartir con ustedes..:-)

 3
Author: yazh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-14 06:16:59

Puede hacer algo como esto (compruebe los posibles valores de los parámetros y métodos similares aquí : https://developer.apple.com/library/ios/documentation/uikit/reference/uiview_class/uiview/uiview.html

[UIView animateWithDuration:duration
                      delay:delay
                    options:option 
                 animations:^{
                     //fade in here (changing alpha of UILabel component)
                 } 
                 completion:^(BOOL finished){
                    if(finished){
                      //start a fade out here when previous animation is finished (changing alpha of UILabel component)
                 }];
}
 2
Author: Julian Król,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-02 20:59:39

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];
}
 2
Author: Bjørn Egil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-17 16:13:00

Respuesta genérica : Puede usar este método para aplicar animación a cualquier objeto UIView . Primero cree una extensión de la clase UIView . Cree un archivo swift separado y escriba el código así

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í self se refiere a cualquier UIView a la que se refiere . Puede usar botones, etiquetas, etc. para llamar a estos 2 métodos .

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

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

Esto da el efecto deseado de animación a cualquier UIObject .

 2
Author: iPhoneDeveloper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-13 11:55:51

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

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

Y añade la llamada fadeOut al bloque 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 tendrá que establecer un delegado ([UIView setAnimationDelegate:(id)delegate]) y un selector con ([UIView setAnimationDidStopSelector:]) al que el delegado responderá.

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

 1
Author: jemmons,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-02 21:02:59

Mi tarea era hacer que una etiqueta se desvaneciera. Y luego se desvanecen 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];

    }];
}
 1
Author: Naloiko Eugene,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-27 09:09:54
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];
    }];
}
 1
Author: Sushree Swagatika,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-20 06:42:57

Le sugiero encarecidamente que utilice una implementación genérica para que pueda reutilizar el código siempre que necesite el efecto de fundido de nuevo.

Debe 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

Entonces, solo tienes que importar el nuevo archivo a tu clase o dentro de tu 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.

Yo también le recomendamos que no parametrice la duración para mantener un patrón a través de toda la aplicación.

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

 1
Author: joao.arruda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-05 14:56:40

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
        })
 0
Author: ArunGJ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-06 20:15:07

Swift 4 Si solo necesita un pulso 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
        })
    }
 0
Author: Nik Kov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-22 15:23:49