为什么我的CAShapeLayer没有动画?(iOS Swift)

jbo*_*row 1 animation core-animation ios swift

在我的一个ViewControllers中,我有addStatus(),粘贴在下面,在我的viewDidLoad.我希望lineWidth这个圆圈能够生成动画,但似乎并没有这样做.在我寻找原因的过程中,我发现了Apple关于动画层内容的文档的这一部分.我认为重要的部分在这里注意到:

如果要使用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")
        })
    }
Run Code Online (Sandbox Code Playgroud)

rob*_*off 6

在我的viewDidLoad.

那是你的问题.该viewDidLoad方法在视图添加到窗口之前运行.除非在窗口中,否则您无法向视图添加动画.通话addStatusviewDidAppear:代替.

另外,不要在动画块中创建新图层.在中创建图层viewDidLoad.