1

I am using a CABasicAnimation that scales a CALayer repeatedly up and down. This means the animation is autoreversing, repeats infinity times, and it's key path is transform.scale.

What I want to do is "fade out" the animation at a certain point. So I don't want to stop it immediately (with layer.removeAnimationForKey:), but I want the animation to be smoothly removed in a time span of, say, one second. I have tried wrapping layer.removeAnimationForKey: in a CATransaction block and setting its animationDuration, but this did not work either.

Any help is appreciated.

return true
  • 7,839
  • 2
  • 19
  • 35

1 Answers1

0

Here is an example of a fade out, which is called when a video I playing with AVPlayer finishes.

override func viewWillAppear(animated: Bool) {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.finishedPlaying(_:)), name: AVPlayerItemDidPlayToEndTimeNotification, object: playerItem)
}

var fadeOut:CABasicAnimation!

func finishedPlaying(myNotification:NSNotification) {

    self.commsRightNow = commsMode.appleTV.rawValue
    fadeOut = CABasicAnimation(keyPath: "opacity")
    fadeOut.fromValue = 1.0
    fadeOut.toValue = 0.0
    fadeOut.duration = 8.0
    fadeOut.delegate = self
    fadeOut.setValue("video", forKey:"fadeOut")
    fadeOut.removedOnCompletion = false
    fadeOut.fillMode = kCAFillModeForwards
    playerLayer.addAnimation(fadeOut, forKey: nil)
}

You can also call the method below to do additional actions when your animation completes. This one removes the AVPlayer object altogether. Note the keys fadeOut and video are user defined values and included since you may have multiple animations starting (&stopping) that you need to identify.

override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
    let nameValue = anim.valueForKey("fadeOut") as? String
    if let name = nameValue {
        if (name == "video") {
            playerLayer?.removeFromSuperlayer()


        }
    }

You can also call this to be triggered when you animation starts.

override func animationDidStart(anim: CAAnimation) {
    // Blah Blah
}
user3069232
  • 8,587
  • 7
  • 46
  • 87
  • Thank you. But I don't think this answer achieves what I want. I don't want a layer to be faded out; I want an animation itself to be faded out. My animation changes the scale of a transform repeatedly from 1 to 1.5 and vice versa. I want this effect to be faded out smoothly so that the scale is 1 (default) at the end. – return true Apr 08 '16 at 12:52