如何在UIButton上运行原生“脉冲效果”动画 - iOS

时间:2011-11-10 16:46:33

标签: ios objective-c animation uikit

我想在UIButton上使用某种脉冲动画(无限循环“缩小比例尺”),以便立即引起用户的注意。

我看到了这个链接How to create a pulse effect using -webkit-animation - outward rings,但我想知道是否有任何方法只使用原生框架来做到这一点?

4 个答案:

答案 0 :(得分:190)

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

<强>夫特

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"

答案 1 :(得分:26)

这是它的快速代码;)

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

答案 2 :(得分:8)

swift代码缺少fromValue,我必须添加它以使其正常工作。

pulseAnimation.fromValue = NSNumber(float: 0.0)

还应设置forKey,否则removeAnimation不起作用。

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

答案 3 :(得分:3)

func animationScaleEffect(view:UIView,animationTime:Float)
{
    UIView.animateWithDuration(NSTimeInterval(animationTime), animations: {

        view.transform = CGAffineTransformMakeScale(0.6, 0.6)

        },completion:{completion in
            UIView.animateWithDuration(NSTimeInterval(animationTime), animations: { () -> Void in

                view.transform = CGAffineTransformMakeScale(1, 1)
            })
    })

}


@IBOutlet weak var perform: UIButton!

@IBAction func prefo(sender: AnyObject) {
    self.animationScaleEffect(perform, animationTime: 0.7)
}