Swift 中的链接动画

Chaining Animations in Swift

最近做了一些画脸的代码。我想让脸动画来回摇晃。目前我有这段代码。它向右旋转一次,然后向左旋转一次,最后回到原来的位置。但是,如果我想让头部来回无限摇晃(来回旋转浴缸)怎么办?是否可以使用某种递归函数来执行此操作?

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

}

您可以从最后的完成块调用 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)
                            }
                            )
                        }
                }
                )
            }
    }
    )
}

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