2015-04-05 81 views
1

在我的其中一個ViewControllers中,我在viewDidLoad的下面粘貼了addStatus()。我期望這個圈子的lineWidth有動畫效果,但似乎沒有這樣做。在我爲什麼會這樣搜索時,我在Animating Layer Content上發現了蘋果文檔的這部分內容。我認爲重要的部分是:爲什麼我的CAShapeLayer不能動畫? (iOS Swift)

如果要使用Core Animation類來啓動動畫,則必須從基於視圖的動畫塊中發出所有Core Animation調用。 UIView類默認禁用圖層動畫,但在動畫塊內重新啓用它們。因此,您在動畫塊外進行的任何更改都不會生成動畫。清單3-5顯示了一個如何顯式地隱式更改圖層的不透明度及其位置的示例。在這個例子中,myNewPosition變量被事先計算並被塊捕獲。兩個動畫同時開始,但不透明動畫以默認計時運行,而位置動畫以其動畫對象中指定的時間運行。

當我查找爲什麼這可能不是動畫時,我讀了這篇文章,並假設它意味着我應該把我的CAAnimation放在一個UIView動畫塊中。這個功能在沒有動畫塊的空白應用程序中工作良好,當放置在rootViewController時,但在我的次要viewController在這個應用程序似乎並不動畫。任何提示都會非常有幫助。謝謝!

func addStatus() { 

     UIView.animateWithDuration(NSTimeInterval.infinity, animations: {() -> Void in 

      let patientZeroIndicator = CAShapeLayer() 

      let radius:CGFloat = 20.0 
      let center:CGPoint = CGPointMake(self.view.frame.width - radius - 10, radius + 10) 
      let startAngle = 0.0 
      let endAngle = 2.0 * Double(M_PI) 

      patientZeroIndicator.lineWidth = 10.0 
      patientZeroIndicator.fillColor = UIColor(netHex: cs_red).CGColor 
      patientZeroIndicator.strokeColor = UIColor.whiteColor().CGColor 
      patientZeroIndicator.path = UIBezierPath(arcCenter: center, radius: radius, startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: true).CGPath 
      self.view.layer.addSublayer(patientZeroIndicator) 

      // Create a blank animation using the keyPath "cornerRadius", the property we want to animate 
      let pZeroAnimation = CABasicAnimation(keyPath: "lineWidth") 

      // Define the parameters for the tween 
      pZeroAnimation.fromValue = 10.0 
      pZeroAnimation.toValue = 5.0 
      pZeroAnimation.autoreverses = true 
      pZeroAnimation.duration = 3.0 
      pZeroAnimation.repeatDuration = CFTimeInterval.infinity 
      pZeroAnimation.timingFunction = CAMediaTimingFunction(controlPoints: 0.25, 0, 0.75, 1) 

      // Finally, add the animation to the layer 
      patientZeroIndicator.addAnimation(pZeroAnimation, forKey: "lineWidth") 
     }) 
    } 

回答

4

在我viewDidLoad

這就是你的問題。在視圖添加到窗口之前運行viewDidLoad方法。除非它在窗口中,否則您不能將動畫添加到視圖。改爲撥打。

另外,不要在您的動畫塊中創建新圖層。在viewDidLoad中創建圖層。

+0

感謝羅布,就是這樣。非常明確的解釋。 – jbobrow 2015-04-05 18:06:40