[Swift]: Create Fade in/out Effect with UIImageView/UIView

swift

05/10/2019


How to make fade in/out effect in Swift 5

This can works with both UIView and UIImageview

1) Create an outlet

SWIFT
@IBOutlet weak var tooltipMessage: UIImageView!

2)

SWIFT
@IBAction func Btn() {
self.tooltipMessage.alpha = 0.0
// Fade in
if tooltipMessage.alpha == 0.0 {
UIImageView.animate(withDuration: 2.0, delay: 0.2, options: .curveEaseIn, animations: {
self.tooltipMessage.alpha = 0.0
} )
}
// Fade out
else {
UIImageView.animate(withDuration: 2.0, delay: 0.2, options: .curveEaseIn, animations: {
self.tooltipMessage.alpha = 1.0
} )
}
}

Hitting the button will start the fade in, and hitting another will fade it out

+) Fading out only

If you want the animation at the start of the view, make sure to put in viewDidAppear() not in viewDidLoad() which may be too early.
For example, if you'd like to show the image at start and make it only fade out

SWIFT
override func viewDidAppear(_ animated: Bool) {
// UIImage should've been set. Otherwise, set it with the following (filename from Assets.xcassets):
// tooltipMessage.image = UIImage(named: "filename")
self.tooltipMessage.alpha = 1.0
if tooltipMessage.alpha == 1.0 {
UIImageView.animate(withDuration: 1.0, delay: 2.0, options: .curveEaseInOut, animations: {
self.tooltipMessage.alpha = 0.0
} )
}
}

WRITTEN BY

Keeping a record