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

前端 未结 4 771
梦如初夏
梦如初夏 2020-12-02 04:28

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 Ho

相关标签:
4条回答
  • 2020-12-02 04:45
    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"

    0 讨论(0)
  • 2020-12-02 04:48
    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)
    }
    
    0 讨论(0)
  • 2020-12-02 04:59

    Here is the swift code for it ;)

    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)
    
    0 讨论(0)
  • 2020-12-02 05:01

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

    pulseAnimation.fromValue = NSNumber(float: 0.0)
    

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

    self.view.layer.addAnimation(pulseAnimation, forKey: "layerAnimation")
    
    0 讨论(0)
提交回复
热议问题