iosswiftuikitcaanimation

Get UIVIew from CAAnimation


I am trying to get UIView object from CAAnimation. I have implemented the following CAAnimationDelegate method

public func animationDidStop(_ animation:CAAnimation, finished:Bool) {
     // Need respective View from "animation:CAAnimation"
}

This class will be performing multiple animations with different views. So I need to find out which View's animation is completed in this delegate method. Please guide me if there is any possibility to get the view from this animation.


Solution

  • As matt suggested here is the way you can find which animation has been completed.

    First of all you need to add different key value to your animation when you are creating it like shown below:

    let theAnimation = CABasicAnimation(keyPath: "opacity")
    theAnimation.setValue("animation1", forKey: "id")
    theAnimation.delegate = self
    
    let theAnimation2 = CABasicAnimation(keyPath: "opacity")
    theAnimation2.setValue("animation2", forKey: "id")
    theAnimation2.delegate = self
    

    And in animationDidStop method you can identify animations:

    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
    
        if let val = anim.value(forKey: "id") as? String {
            switch val {
            case "animation1":
                print("animation1")
            case "animation2":
                print("animation2")
            default:
                break
            }
        }
    }
    

    I have taken THIS answer and converted Objective c code to swift with switch case.