Core Animation - modify animation property

后端 未结 3 932
没有蜡笔的小新
没有蜡笔的小新 2020-12-21 13:47

I have animation

 func startRotate360() {
    let rotation : CABasicAnimation = CABasicAnimation(keyPath: \"transform.rotation.z\")
    rotation.fromValue =          


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-21 14:04

    Maybe this is not the best solution but it works, as you say you can not modify properties of the CABasicAnimation once is created, also we need to remove the rotation.repeatCount = Float.greatestFiniteMagnitude, if notCAAnimationDelegatemethodanimationDidStop` is never called, with this approach the animation can be stoped without any problems as you need

    step 1: first declare a variable flag to mark as you need stop animation in your custom class

    var needStop : Bool = false
    

    step 2: add a method to stopAnimation after ends

    func stopAnimation()
    {
        self.needStop = true
    }
    

    step 3: add a method to get your custom animation

    func getRotate360Animation() ->CAAnimation{
        let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotation.fromValue = 0
        rotation.toValue =  Double.pi * 2
        rotation.duration = 1
        rotation.isCumulative = true
        rotation.isRemovedOnCompletion = false
        return rotation
    }
    

    step 4: Modify your startRotate360 func to use your getRotate360Animation() method

    func startRotate360() {
        let rotationAnimation = self.getRotate360Animation()
        rotationAnimation.delegate = self
        self.layer.add(rotationAnimation, forKey: "rotationAnimation")
    }
    

    step 5: Implement CAAnimationDelegate in your class

    extension YOURCLASS : CAAnimationDelegate
    {
    
        func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
            if(anim == self.layer?.animation(forKey: "rotationAnimation"))
            {
                self.layer?.removeAnimation(forKey: "rotationAnimation")
                if(!self.needStop){
                    let animation = self.getRotate360Animation()
                    animation.delegate = self
                    self.layer?.add(animation, forKey: "rotationAnimation")
                }
            }
        }
    }
    

    This works and was tested

    Hope this helps you

提交回复
热议问题