如何做一个本地人;“脉冲效应”;UIButton上的动画-iOS

如何做一个本地人;“脉冲效应”;UIButton上的动画-iOS,ios,objective-c,animation,uikit,Ios,Objective C,Animation,Uikit,我想在UIButton上有一些脉冲动画(无限循环“缩放入-缩放出”),这样可以立即引起用户的注意 我看到了这个链接,但我想知道是否只有使用本机框架才能做到这一点 CABasicAnimation *theAnimation; theAnimation=[CABasicAnimation animationWithKeyPath:@"opacity"]; theAnimation.duration=1.0; theAnimation.repeatCount=HUGE_VALF; theAnima

我想在UIButton上有一些脉冲动画(无限循环“缩放入-缩放出”),这样可以立即引起用户的注意

我看到了这个链接,但我想知道是否只有使用本机框架才能做到这一点

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")

这是它的swift代码;)


swift代码缺少一个
fromValue
,我必须添加它才能使其正常工作

pulseAnimation.fromValue = NSNumber(value: 0.0)
还应设置
forKey
,否则
removeAnimation
不起作用

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

谢谢你的回答!不过我得说我有点困了。我对CALayer一点也不熟悉,也不知道如何将它与我的UIButton联系起来。加上你的代码看起来像是在改变不透明度,而不是比例。好的“脉冲动画”是一个通常用于闪烁效果的术语,如该链接中的示例所述。现在我重读你的问题,明白你想要什么。首先,每个视图都有自己的层。若QartzCore框架被添加到项目中,那个么只需键入
myView.layer
即可访问它。可以使用核心动画设置层动画。对于缩放变换,您可以使用这种方法:太棒了!使用@“transform.scale”而不是@“opacity”工作起来很有魅力。谢谢!如果您还没有,您需要添加
#import
,以获取CALayers.UGH的所有定义!除非您正在将实际答案更新为正确的现代版本,否则不要编辑过期的3年答案。添加空格并不是在更新它。特别是不要在三年后复活。所有的分号是怎么回事?;)@分号设置脉冲幅度常数的类型。没有必要使用它,但当赋值的右边没有明确表示将分配什么类型时,它确实会增加代码的清晰度。@ScottChow我想你是在说冒号。我的评论是对最初答案的一个玩笑,因为不需要分号和Swift连用。我猜答案经过多次编辑后就不那么明显了:)请确保添加fromValue
self.view.layer.addAnimation(pulseAnimation, forKey: "layerAnimation")
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)
}