2017-01-10 122 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

謝謝你的作品。 –