Reputation: 33
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)
}
}
Upvotes: 2
Views: 651
Reputation: 527
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()
}
Upvotes: 2
Reputation: 13679
Your code works fine for me inside a playground:
import UIKit
import XCPlayground
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)
}
}
let liveView = UIView(frame: CGRect(origin: CGPointZero, size: CGSize(width: 400, height: 400)))
XCPlaygroundPage.currentPage.liveView = liveView
let newView = UIView(frame: CGRect(x: 200, y: 200, width: 50, height: 50))
newView.backgroundColor = UIColor.greenColor()
newView.alpha = 0
liveView.addSubview(newView)
newView.fadeIn { _ in newView.fadeOut{ _ in newView.fadeIn() } }
It fades in, fades out on completion of the fade-in, then fades back in on completion of the fade-out.
Perhaps the issue it where / when you are calling the fadeIn()
method on your view, and not a problem with your extension itself.
Upvotes: 1