Search code examples
iosswiftcaanimationcakeyframeanimation

CAKeyframeAnimation key times after 1.0 sec not executing


For some strange reason when I put in key times after 1 second they don't appear to execute but when I keep all my key times 1 second and under they all execute properly. Not sure why this is happening, anyone have any ideas? This is the function I'm using:

 func animateKeyFrameGroup() {

let opacity = CAKeyframeAnimation(keyPath: "opacity")
opacity.values = [1, 0, 1]
opacity.keyTimes = [0.1, 1.0, 1.5]

let translation =  CAKeyframeAnimation(keyPath:"transform.translation")
translation.values = [CGPoint(x: 150, y: 300),CGPoint(x: 100, y: 100),CGPoint(x: 150, y: 300)]
translation.keyTimes = [0.1, 1.0, 1.5]

let cornerRadius =  CAKeyframeAnimation(keyPath: "cornerRadius")
cornerRadius.values = [circle.bounds.width, circle.bounds.width/2, circle.bounds.width]
cornerRadius.keyTimes = [0.1, 1.0, 1.5]

let borderColor =  CAKeyframeAnimation(keyPath: "borderColor")
borderColor.values = [UIColor.black.cgColor, UIColor.cyan.cgColor, UIColor.black.cgColor]
borderColor.keyTimes = [0.1, 1.0, 1.5]

let keyframeAnimationGroup = CAAnimationGroup()
keyframeAnimationGroup.animations = [translation, cornerRadius, borderColor, opacity]
keyframeAnimationGroup.duration = 2
keyframeAnimationGroup.isRemovedOnCompletion = false
keyframeAnimationGroup.fillMode = kCAFillModeForwards
circle.layer.add(keyframeAnimationGroup, forKey: nil)
  }

Solution

  • According to Apple documentation:

    Each value in the array is a floating point number between 0.0 and 1.0 that defines the time point (specified as a fraction of the animation’s total duration) at which to apply the corresponding keyframe value. Each successive value in the array must be greater than, or equal to, the previous value. Usually, the number of elements in the array should match the number of elements in the values property or the number of control points in the path property. If they do not, the timing of your animation might not be what you expect.

    So you can change a total animation duration: keyframeAnimationGroup.duration = 2

    and keyTimes are the fractions of the total duration. Like: keyTime equal 0.5 -> 2 * 0.5 = 1 sec, keyTime equal 0.75 -> 2 * 0.75 = 1.5 sec, etc.