Fade In and Fade out in Animation Swift
Starting from iOS 10 Apple launched new iOS Animations SDK that is much more powerful, especially concerning timings functions and interactivity.
Fade out code with this approach will:
UIViewPropertyAnimator(duration: 0.5, curve: .easeOut, animations: {
self.uiImageView.alpha = 0.0
}).startAnimation()
To get more details about the Property Animator, take a look at iOS 10 Animations demo.
Swift 4 . Add fade in and fade out function to UIView object
extension UIView {
func fadeIn(_ duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, completion: @escaping ((Bool) -> Void) = {(finished: Bool) -> Void in}) {
UIView.animate(withDuration: duration, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.alpha = 1.0
}, completion: completion) }
func fadeOut(_ duration: TimeInterval = 0.5, delay: TimeInterval = 1.0, completion: @escaping (Bool) -> Void = {(finished: Bool) -> Void in}) {
UIView.animate(withDuration: duration, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.alpha = 0.3
}, completion: completion)
}
}
Example
label.fadeIn()
label.fadeOut()
imageView.fadeOut(completion: {
(finished: Bool) -> Void in
imageView.removeFromSuperview()
})
label.fadeIn(completion: {
(finished: Bool) -> Void in
label.text = "Changed!"
})
This is what I would do based on my research: (Supposing you're using storyboard)
Go to your UIImageView, and under the Attributes, check the "User Interaction Enabled" checkbox.
Drag a TapGestureRecognizer on top of the image view.
Control click on the Tap Gesture and drag to make a action on your ViewControler.swift.
Add the following code inside:
UIView.animate(withDuration: 0.5, delay: 0.5, options: .curveEaseOut, animations: { self.uiImageView.alpha = 0.0 }, completion: nil)
Then you're done!