Fabian Boulegue
Fabian Boulegue

Reputation: 6608

How to wait until an animation is finished in Swift?

I try to let a button "shake" before the next question of my quiz is going to load.

The animation looks like

var timer = NSTimer()
    UIView.animateWithDuration(0.1, animations: {
        self.IMGVIEWcat.center = CGPointMake(self.IMGVIEWcat.center.x + 2, self.IMGVIEWcat.center.y)
    })
    UIView.animateWithDuration(0.2, animations: {
        self.IMGVIEWcat.center = CGPointMake(self.IMGVIEWcat.center.x - 4, self.IMGVIEWcat.center.y)
    })
    UIView.animateWithDuration(0.3, animations: {
            self.IMGVIEWcat.center = CGPointMake(self.IMGVIEWcat.center.x + 2, self.IMGVIEWcat.center.y)
    })

After this the following function is called

    func QueryInformations(){
        println("QueryInformationsStart")
        self.ActivityIndicator.hidden = false
        ObjectIDsArrayCount = ObjectIDsArray.count
        var RandomQuestion = Int(arc4random_uniform(ObjectIDsArray.count + 0))
        var QuestionID:String = ObjectIDsArray[RandomQuestion]
        var query : PFQuery = PFQuery(className: "AddonQuiz")
        query.getObjectInBackgroundWithId(QuestionID){
            (ObjectHolder : PFObject!, error : NSError!) -> Void in
...

Now the animation starts but instant the next question is loaded, is there some easy wait for a beginner to implement a "waiting" until the animation is done?

I tried to set

var complet == true 

In the animation

And in the query function

if complet = true {....

But this did not work for me, also I found some information about completion handler but didn't get it work in my code.

Upvotes: 2

Views: 21632

Answers (2)

Ian MacDonald
Ian MacDonald

Reputation: 14030

Use the completion block on that function you're calling:

UIView.animateWithDuration(0.3, animations: {
        self.IMGVIEWcat.center = CGPointMake(self.IMGVIEWcat.center.x + 2, self.IMGVIEWcat.center.y)
}, completion: {(finished:Bool) in
  QueryInformations()
})

Upvotes: 1

Cesare
Cesare

Reputation: 9419

If you want to use the completion block at the end of the animation, you should use constructs with the delay and options arguments as well.

UIView.animateWithDuration(0.3, delay: 0.0, options: UIViewAnimationOptions.CurveLinear, animations: { 
// put here the code you would like to animate
    self.IMGVIEWcat.center = CGPointMake(self.IMGVIEWcat.center.x + 2, self.IMGVIEWcat.center.y)

}, completion: {(finished:Bool) in
// the code you put here will be compiled once the animation finishes
    QueryInformations() 
})

Upvotes: 9

Related Questions