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
Swift only solution
Similar to Luca's anwer, I use a UIView
extension. Compared to his solution I use DispatchQueue.main.async
to make sure animations are done on the main thread, alpha
parameter for fading to a specific value and optional duration
parameters for cleaner code.
extension UIView {
func fadeTo(_ alpha: CGFloat, duration: TimeInterval = 0.3) {
DispatchQueue.main.async {
UIView.animate(withDuration: duration) {
self.alpha = alpha
}
}
}
func fadeIn(_ duration: TimeInterval = 0.3) {
fadeTo(1.0, duration: duration)
}
func fadeOut(_ duration: TimeInterval = 0.3) {
fadeTo(0.0, duration: duration)
}
}
How to use it:
// fadeIn() - always animates to alpha = 1.0
yourView.fadeIn() // uses default duration of 0.3
yourView.fadeIn(1.0) // uses custom duration (1.0 in this example)
// fadeOut() - always animates to alpha = 0.0
yourView.fadeOut() // uses default duration of 0.3
yourView.fadeOut(1.0) // uses custom duration (1.0 in this example)
// fadeTo() - used if you want a custom alpha value
yourView.fadeTo(0.5) // uses default duration of 0.3
yourView.fadeTo(0.5, duration: 1.0)