在 swift 中延迟运行动画



我有一个脉冲动画,我想运行 3 或 4 秒,正在寻找一种方法来延迟并运行该动画一段时间,然后再进入下一个屏幕。 我正在使用下面的代码进行延迟,但是当我调用该函数时它不起作用。

NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: "functionHere", userInfo: nil, repeats: false)

如果您有任何想法,请告诉我。

let pulseAnimation = CABasicAnimation(keyPath: "opacity")
    pulseAnimation.duration = 1
    pulseAnimation.fromValue = 0
    pulseAnimation.toValue = 1
    pulseAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    pulseAnimation.autoreverses = true
    pulseAnimation.repeatCount = FLT_MAX
    XboxOneL.layer.addAnimation(pulseAnimation, forKey: "animateOpacity")
    XboxOneR.layer.addAnimation(pulseAnimation, forKey: "animateOpacity")

根据动画的实现方式,可以使用:

UIView.animate(withDuration: 0.3, delay: 5.0, options: [], animations: { 
//Animations
}) { (finished) in
//Perform segue
}

这将在动画运行之前应用延迟,然后运行完成块(执行 segue 的位置(。

编辑:您更新了您的问题以使用CAAnimations,所以我认为此解决方案不起作用。

如果您正在寻找 Swift 3 中标准的延迟,那么最好将 DispatchQueue API 与 UIView.animate(withDuration:_:) 结合使用。

例如,如果您想将 1.0 秒的动画延迟 3 秒:

let yourDelay = 3
let yourDuration = 1.0
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(yourDelay), execute: { () -> Void in
    UIView.animate(withDuration: yourDuration, animations: { () -> Void in
        // your animation logic here
    })
})

让我知道这对你是否有意义

利用 UIView.animate(withDuration:( 的完成处理程序。基本示例如下:

func performMyAnimation() {
  UIView.animate(withDuration: {$duration}, 
      animations: { /* Animation Here */ }, 
      completion: { _ in self.performSegue(withIdentifier: "segueIdentifierHere", sender: nil) }
}

动画在animations块中运行。完成后,您将执行下一个屏幕的 segue。


编辑:由于问题现在包括动画代码,使用 CABasicAnimation ,那么也许这个 CAAnimation 回调的答案可能对您有用。

基本上,您需要用CATransaction包装CABasicAnimation通话。

CATransaction.begin()
CATransaction.setCompletionBlock({
    self.performSegue(withIdentifier: "segueIdentifierHere", sender: nil)
})
// Your animation here
CATransaction.commit()

在 Swift 4 中,您可以将 @Michael Fourre 的示例重写为:

let yourDelay = 3.0
    let yourDuration = 1.0
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + yourDelay, execute: { () -> Void in
        UIView.animate(withDuration: yourDuration, animations: { () -> Void in
            // your animation logic here
        })
    })

最新更新