Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fade In Fade Out Animation

Here is some code I struggle with for a while.

If you start the fade in animation, the label text fades in. If I start the fade out animation the the label text fades out.

When I start the startFade method, only fade out is shown. How can I wait for the fadeIn method to finish visually before starting the fadeOut method.

-(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]; } 
like image 523
SoTm Avatar asked Jan 02 '14 20:01

SoTm


People also ask

What is fade-in and fade-out in animation?

In android, Fade In and Fade Out animations are used to change the appearance and behavior of the objects over a particular interval of time. The Fade In and Fade Out animations will provide a better look and feel for our applications.

How do I fade fade-out animation in CSS?

In the CSS, use the @keyframes rule paired with fadeIn. At 0%, set the opacity to 0. At 100%, set the opacity to 1. This creates the fade-in effect.

What is difference between fade-in and fade-out?

A fade-in effect begins with a solid color (Movie Maker supports both black and white) and then fades into your video. A fade-out effect begins with the video and then fades into the solid color, again either black or white.


1 Answers

When you call the fadeIn and fadeOut methods back to back like you're doing, the code is run instantaneously, so you'll only see animation from the last method called. UIView block based animation provides a completion handler, which seems to be exactly what you're looking for. So your code might looks something like this:

-(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         })     } } 
like image 159
hgwhittle Avatar answered Oct 14 '22 13:10

hgwhittle