swiftanimationcabasicanimation

Swift stop CABasicAnimation


Im used CABasicAnimation for animate view like pulse frame

Have code

extension UIView {
/// animate the border width
func animateBorderWidth(toValue: CGFloat, duration: Double) -> CABasicAnimation {
    let widthAnimation = CABasicAnimation(keyPath: "borderWidth")
    widthAnimation.fromValue = 0.9
    widthAnimation.toValue = 0.0
    widthAnimation.duration = 15
    widthAnimation.timingFunction = CAMediaTimingFunction(name: .easeOut)
    return widthAnimation
}

/// animate the scale
func animateScale(toValue: CGFloat, duration: Double) -> CABasicAnimation {
    let scaleAnimation = CABasicAnimation(keyPath: "transform.scale")
    scaleAnimation.fromValue = 1.0
    scaleAnimation.toValue = 12
    scaleAnimation.duration = 55
    scaleAnimation.repeatCount = .infinity
    scaleAnimation.isRemovedOnCompletion = false
    scaleAnimation.timingFunction = CAMediaTimingFunction(name: .linear)
    return scaleAnimation
}
    
func pulsate(animationDuration: CGFloat) {
    var animationGroup: CAAnimationGroup!
    let newLayer = CALayer()
    animationGroup = CAAnimationGroup()
    animationGroup.duration = CFTimeInterval(animationDuration)
    animationGroup.repeatCount = Float.infinity
    
    newLayer.bounds = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
    newLayer.cornerRadius = self.frame.width/2
    newLayer.position = CGPoint(x: self.frame.width/2, y: self.frame.height/2)
    newLayer.cornerRadius = self.frame.width/2
    newLayer.borderColor = #colorLiteral(red: 0.7215686275, green: 0.5137254902, blue: 0.7647058824, alpha: 0.7).cgColor
    
        animationGroup.timingFunction = CAMediaTimingFunction(name: .easeOut)
    animationGroup.animations = [animateScale(toValue: 7.5, duration: 2.0),
                                 animateBorderWidth(toValue: 0.6, duration: Double(animationDuration))]
        animationGroup.duration = 14
    newLayer.add(animationGroup, forKey: "pulse")
    self.layer.cornerRadius = self.frame.width/2
    self.layer.insertSublayer(newLayer, at: 0)
}

func removeAnimation() {
    self.layer.sublayers?.forEach { $0.removeAnimation(forKey: "pulse") }
}

} enter image description here

And add in UIViewCOntroller this animation to view

func startPul() {
self.backPulseView.pulsate(animationDuration: 2.0)
}

But if I press button I want to stop animation and hide Im trying

func stopPul() {
self.backPulseView.removeAnimation()
}

But animation still working and dos't removed

How can I remove animation and then I can call again?

stop animation I call from button tap

 @IBAction func stopBtn(_ sender: UIButton) {
    stopPul()
 }

Solution

  • To remove the animation iterate through sublayers and remove animation for that "pulse" key:

    self.layer.sublayers?.forEach {
                $0.speed = 0
                $0.removeAllAnimations()
                $0.removeFromSuperlayer()
            }
    }