swiftcore-animationcaanimation

How to animate sublayer contents?


I have a layer and want to create an animation for this layer which will update contents of one of sublayers. CAAnimation keyPath has a notation, like sublayers.layerName.propertyName to update some values of a sublayer but seems like it doesn't work with .contents property.

    func rightStepAfter(_ t: Double) -> CAAnimation {
        let rightStep = CAKeyframeAnimation(keyPath: "sublayers.right.contents")
        rightStep.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
        rightStep.keyTimes = [0, 1]
        rightStep.values = [UIImage(named:"leftfoot")!.cgImage!, UIImage(named:"rightfoot")!.cgImage!]
        rightStep.beginTime = t
        rightStep.duration = stepDuration
        rightStep.fillMode = .forwards
        return rightStep
    }
    func leftStepAfter(_ t: Double) -> CAAnimation {
        let leftStep = CAKeyframeAnimation(keyPath: "sublayers.left.opacity")
        leftStep.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
        leftStep.keyTimes = [0, 1]
        leftStep.values = [0, 1]
        leftStep.beginTime = t
        leftStep.duration = stepDuration
        leftStep.fillMode = .forwards
        return leftStep
    }

Here leftStepAfter creates correct animation which updates opacity of a sublayer and rightStepAfter doesn't update contents of a sublayer. If you remove sublayers.right. from the keyPath - animation will correctly change contents of a CURRENT layer. Project to check it and the original project.

Why my animation doesn't work and how to fix it?


Solution

  • Did not find an answer to my original question (via keypath), but solved my problem by creating several animations for each sublayer.