Swift中的链接动画

时间:2017-01-10 04:15:39

标签: ios swift animation recursion drawing

最近,我制作了一些画面的代码。我想动画脸部来回摇晃。目前我有这个代码。它向右旋转一次,然后向左旋转,然后旋转到原始位置。但是,如果我想让头部无限地来回摇动(旋转浴缸和向前),该怎么办?有可能做一些递归函数来做到这一点吗?

@IBAction func shakeHead(_ sender: UITapGestureRecognizer) {

    UIView.animate(
        withDuration: 0.5,
        animations: {
            self.faceView.transform = self.faceView.transform.rotated(by: self.shakeAngle)
    },
        completion:{ finished in
            if(finished){
                UIView.animate(
                    withDuration: 0.5,
                    animations: {
                        self.faceView.transform = self.faceView.transform.rotated(by: -(self.shakeAngle)*2)
                },
                    completion:{ finished in
                        if(finished){
                            UIView.animate(
                                withDuration: 0.5,
                                animations: {
                                    self.faceView.transform = self.faceView.transform.rotated(by: self.shakeAngle)
                            },
                                completion: nil
                            )
                        }
                }
                )
            }
    }
    )

}

1 个答案:

答案 0 :(得分:2)

您可以从最终完成块中调用shakeHead

@IBAction func shakeHead(_ sender: UITapGestureRecognizer) {

    UIView.animate(
        withDuration: 0.5,
        animations: {
            self.faceView.transform = self.faceView.transform.rotated(by: self.shakeAngle)
    },
        completion:{ finished in
            if(finished){
                UIView.animate(
                    withDuration: 0.5,
                    animations: {
                        self.faceView.transform = self.faceView.transform.rotated(by: -(self.shakeAngle)*2)
                },
                    completion:{ finished in
                        if(finished){
                            UIView.animate(
                                withDuration: 0.5,
                                animations: {
                                    self.faceView.transform = self.faceView.transform.rotated(by: self.shakeAngle)
                            },
                                completion: { finished in
                                    shakeHead(sender)
                            }
                            )
                        }
                }
                )
            }
    }
    )
}

即使这在技术上是递归调用,但由于代码的异步性质,这不是问题。