Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a simple fade in animation in Swift?

Tags:

ios

swift

I am trying to make a simple animation in Swift. It is a fade in.

I attempted:

self.myFirstLabel.alpha = 0 self.myFirstButton.alpha = 0 self.mySecondButton.alpha = 0 

Then, I have:

self.view.addSubview(myFirstLabel) self.view.addSubview(myFirstButton) self.view.addSubview(mySecondButton) 

And then:

UIView.animateWithDuration(1.5, animations: {  self.myFirstLabel.alpha = 1.0  self.myFirstButton.alpha = 1.0  self.mySecondButton.alpha = 1.0 }) 

I have all of this in my viewDidLoad function.

How do I make this work?

like image 644
Benr783 Avatar asked Jun 08 '14 23:06

Benr783


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.

Is fade part of animation?

Fade-in animation is just one of many types of animation you can implement on your website. There are hover animations, loading animations, and dozens of other animation examples.


1 Answers

The problem is that you're trying start the animation too early in the view controller's lifecycle. In viewDidLoad, the view has just been created, and hasn't yet been added to the view hierarchy, so attempting to animate one of its subviews at this point produces bad results.

What you really should be doing is continuing to set the alpha of the view in viewDidLoad (or where you create your views), and then waiting for the viewDidAppear: method to be called. At this point, you can start your animations without any issue.

override func viewDidAppear(_ animated: Bool) {     super.viewDidAppear(animated)      UIView.animate(withDuration: 1.5) {         self.myFirstLabel.alpha = 1.0         self.myFirstButton.alpha = 1.0         self.mySecondButton.alpha = 1.0     } } 
like image 138
Mick MacCallum Avatar answered Sep 29 '22 07:09

Mick MacCallum