Search code examples
iosswiftcore-animation

CAShapeLayer Not Updating in Animation


I have got a CAShapeLayer containing a basic shape, which is created during the 'drawRect' method, which can be seen below.

override func drawRect(frame: CGRect)
    {
        let rectangleRect = CGRectMake(frame.minX + 2.5, frame.minY + 2.5, frame.width - 5, frame.height - 5)
        let rectanglePath = UIBezierPath(roundedRect: rectangleRect, cornerRadius: 4)
        shapeLayer.path = rectanglePath.CGPath

        if (self.active == true)
        {
            shapeLayer.fillColor = selectedColor.CGColor
        } else
        {
            shapeLayer.fillColor = buttonColor.CGColor
        }

        shapeLayer.strokeColor = buttonOutlineColor.CGColor
        shapeLayer.lineWidth = 5.0

        self.layer.addSublayer(shapeLayer)

    }

I use this to create a simple square, with a stroke. I then have another method, which has an animation for the CAShapeLayer. However, when the method is called, nothing is changed on the CAShapeLayer. The animation method is show below.

let animation = CABasicAnimation(keyPath: "strokeColor")
    animation.duration = 0.5
    animation.repeatCount = 10
    animation.fromValue = UIColor.whiteColor()
    animation.toValue = UIColor.redColor()
    animation.autoreverses = true
    shapeLayer.addAnimation(animation, forKey: "strokeColor")

The variable shapeLayer has been defined at the top of the Class. I am very interested in why this does not work. Any advice on how to fix this will be greatly appreciated!


Solution

  • This is an issue that plagues me every time I use Quartz/CoreGraphics. The fromValue and toValue need CGColor parameters, and not UIColor.

    Just change it so that they're UIColor.whiteColor().CGColor and UIColor.redColor().CGColor

    In general, if you're using the prefix CA or CG, you're going to want to use CGColor et al.