Below is my code. The fade out effect works fine. The fade in effect however is not animated . I can not solve this problem. Thanks to all those that will help me. Alpha is set 0 in storyboard
extension UIView {
func fadeIn(duration: NSTimeInterval = 3.0, delay: NSTimeInterval = 0.0, completion: ((Bool) -> Void) = {(finished: Bool) -> Void in}) {
UIView.animateWithDuration(duration, delay: delay, options: UIViewAnimationOptions.CurveLinear, animations: {
self.alpha = 1.0
}, completion: completion) }
func fadeOut(duration: NSTimeInterval = 2.0, delay: NSTimeInterval = 3.0, completion: (Bool) -> Void = {(finished: Bool) -> Void in}) {
UIView.animateWithDuration(duration, delay: delay, options: UIViewAnimationOptions.CurveEaseOut, animations: {
self.alpha = 0.0
}, completion: completion)
}
}
Calling UIView.animationWithDuration
directly after it was called will cancel the previous animation even if you supply a delay in the function call. However, you can either use the completion function like @Daniel Hall suggested:
myView.fadeIn() { _ in
myView.fadeOut()
}
Or if you do the fadeOut in a different method that is being triggered by some event exactly after fadeIn you can use dispatch_after to execute after delay time ( which should be the fadeIn duration in your case)
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
self.myView.fadeOut()
}