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?
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.
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.
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With