Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run an animation with delay in swift

Tags:

delay

ios

swift

I have a pulse animation that I want to run for 3 or 4 seconds, and am looking for a way to delay and run that animation for that amount of time before segueing to the next screen. I am using the code below for the delay, but it is not working when I call the function.

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

Please let me know if you have any ideas.

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")
like image 748
dgelinas21 Avatar asked Feb 07 '17 18:02

dgelinas21


2 Answers

Depending on how your animation is implemented, you could use:

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

This will apply a delay before the animations run, then run a completion block (where you execute your segue).

EDIT: You updated your question to use CAAnimations, so I don't think this solution will work.

like image 147
Matt Beaney Avatar answered Oct 20 '22 00:10

Matt Beaney


If you're looking for a delay which is standard in Swift 3, then it's probably best to use the DispatchQueue API in conjunction with UIView.animate(withDuration:_:).

If for example you wanted to delay a 1.0 second animation by 3 seconds:

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

Let me know if this makes sense to you

like image 42
Michael Fourre Avatar answered Oct 20 '22 00:10

Michael Fourre