2015-04-05 78 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