如何等到动画在 Swift 内完成?

How to wait until an animation is finished in Swift?

我尝试在我的测验的下一个问题加载之前让按钮 "shake"。

动画看起来像

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

在此之后调用以下函数

    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
...

现在动画开始,但下一个问题立即加载,是否有一些简单的等待初学者实现 "waiting" 直到动画完成?

我试过设置

var complet == true 

动画中

并且在查询函数中

if complet = true {....

但这对我不起作用,我也找到了一些关于完成处理程序的信息,但没有在我的代码中使用它。

在您调用的函数上使用 completion 块:

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

如果您想在动画结束时使用 completion 块,您还应该使用带有 delayoptions 参数的结构。

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