I am looking to make a label fade in, in viewDidLoad()
, and then after a timer is at 3 fade out. I am not familiar with the fadein
or fadeout
functions.
How would I go about doing this?
My suggestion is to leverage Swift extensions to make the code a bit more modular and easy to use. For example, if you want to make multiple labels fadein/out or one label to fade in/out on multiple views, you would have to pass the animateWithDuration methods everywhere, which can be a hassle. A cleaner alternative is to create a file called UIView.swift (our UIView extension). Add the following code to this file:
import Foundation
extension UIView {
func fadeIn(duration: NSTimeInterval = 1.0, delay: NSTimeInterval = 0.0, completion: ((Bool) -> Void) = {(finished: Bool) -> Void in}) {
UIView.animateWithDuration(duration, delay: delay, options: UIViewAnimationOptions.CurveEaseIn, animations: {
self.alpha = 1.0
}, completion: completion) }
func fadeOut(duration: NSTimeInterval = 1.0, delay: NSTimeInterval = 3.0, completion: (Bool) -> Void = {(finished: Bool) -> Void in}) {
UIView.animateWithDuration(duration, delay: delay, options: UIViewAnimationOptions.CurveEaseIn, animations: {
self.alpha = 0.0
}, completion: completion)
}
}
Now you can add fadeIn/fadeout functionality to any child of UIView (e.g., UILabel, UIImage, etc). Inside of your viewDidLoad() function, you can add :
self.statusLabel.alpha = 0
self.statusLabel.text = "Sample Text Here"
self.myLabel.fadeIn(completion: {
(finished: Bool) -> Void in
self.myLabel.fadeOut()
})
Now, you can use this sample code for Image views, labels, text views, scroll views, or any child of UIView as well. I hope this helps.