How to do a native "Pulse effect" animation on a UIButton - iOS How to do a native "Pulse effect" animation on a UIButton - iOS ios ios

How to do a native "Pulse effect" animation on a UIButton - iOS


CABasicAnimation *theAnimation;theAnimation=[CABasicAnimation animationWithKeyPath:@"opacity"];theAnimation.duration=1.0;theAnimation.repeatCount=HUGE_VALF;theAnimation.autoreverses=YES;theAnimation.fromValue=[NSNumber numberWithFloat:1.0];theAnimation.toValue=[NSNumber numberWithFloat:0.0];[theLayer addAnimation:theAnimation forKey:@"animateOpacity"]; //myButton.layer instead of

Swift

let pulseAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.opacity))pulseAnimation.duration = 1pulseAnimation.fromValue = 0pulseAnimation.toValue = 1pulseAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)pulseAnimation.autoreverses = truepulseAnimation.repeatCount = .greatestFiniteMagnitudeview.layer.add(pulseAnimation, forKey: "animateOpacity")

See the article "Animating Layer Content"


Here is the swift code for it ;)

let pulseAnimation = CABasicAnimation(keyPath: "transform.scale")pulseAnimation.duration = 1.0pulseAnimation.toValue = NSNumber(value: 1.0)pulseAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)pulseAnimation.autoreverses = truepulseAnimation.repeatCount = .greatestFiniteMagnitudeself.view.layer.add(pulseAnimation, forKey: nil)


The swift code is missing a fromValue, I had to add it in order to get it working.

pulseAnimation.fromValue = NSNumber(value: 0.0)

Also forKey should be set, otherwise removeAnimation doesn't work.

self.view.layer.addAnimation(pulseAnimation, forKey: "layerAnimation")