FadeIn动画不能快速工作2

时间:2016-08-19 23:31:59

标签: ios swift animation fadein

以下是我的代码。 淡出效果很好。然而,淡入效果不是动画的。 我无法解决这个问题。感谢所有能帮助我的人。 Alpha在故事板中设置为0

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)
    }

}

2 个答案:

答案 0 :(得分:2)

在调用UIView.animationWithDuration之后直接调用它将取消上一个动画,即使您在函数调用中提供了延迟。但是,您可以使用@Daniel Hall建议的完成功能:

myView.fadeIn() {  _ in
   myView.fadeOut() 
}

或者如果你在fadeIn之后的某个事件触发的另一个方法中执行fadeOut,你可以使用dispatch_after在延迟时间之后执行(在你的情况下应该是fadeIn持续时间)

let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
    self.myView.fadeOut()
}

答案 1 :(得分:1)

你的代码在游乐场内适合我:

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() } }

淡入淡出,淡入完成后逐渐消失,然后在淡出完成后消失。

可能是您在视图中调用fadeIn()方法的位置/时间问题,而不是您的扩展本身的问题。