2017-01-10 75 views
2

最近,我做了一些绘制脸部的代码。我想动画脸部来回摇晃。目前我有这个代码。它向右旋转一次,然后再向左旋转,然后再旋转到原始位置。但是,如果我想让头部来回无限地摇摆(旋转来回走动),该怎么办?是否有可能做某种递归函数来做到这一点?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 
          ) 
         } 
       } 
       ) 
      } 
    } 
    ) 

} 

回答

3

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

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

+0

谢谢你的作品。 –