Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I would like to have some kind of pulse animation (infinite loop "scale in - scale out") on a UIButton so it gets users' attention immediately.

I saw this link How to create a pulse effect using -webkit-animation - outward rings but I was wondering if there was any way to do this only using native framework?

like image 986
Johann Avatar asked Nov 10 '11 16:11

Johann


3 Answers

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 = 1
pulseAnimation.fromValue = 0
pulseAnimation.toValue = 1
pulseAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
pulseAnimation.autoreverses = true
pulseAnimation.repeatCount = .greatestFiniteMagnitude
view.layer.add(pulseAnimation, forKey: "animateOpacity")

See the article "Animating Layer Content"

like image 128
beryllium Avatar answered Oct 23 '22 16:10

beryllium


Here is the swift code for it ;)

let pulseAnimation = CABasicAnimation(keyPath: "transform.scale")
pulseAnimation.duration = 1.0
pulseAnimation.fromValue = NSNumber(value: 0.0)
pulseAnimation.toValue = NSNumber(value: 1.0)
pulseAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
pulseAnimation.autoreverses = true
pulseAnimation.repeatCount = .greatestFiniteMagnitude
self.view.layer.add(pulseAnimation, forKey: nil)
like image 32
Ravi Sharma Avatar answered Oct 23 '22 17:10

Ravi Sharma


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")
like image 10
Bassebus Avatar answered Oct 23 '22 18:10

Bassebus