How to make a button flash or blink?

前端 未结 12 1034
不思量自难忘°
不思量自难忘° 2021-02-01 06:17

I am trying to change a button\'s color (just a flash/blink) to green when a scan is correct and red when there\'s a problem. I am able to do this with a view like so

         


        
12条回答
  •  孤城傲影
    2021-02-01 07:13

    Swift 4:

    I've maked an extension with some useful options:

    extension UIButton {
        open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
            return self.bounds.contains(point) ? self : nil
        }
        func blink(enabled: Bool = true, duration: CFTimeInterval = 1.0, stopAfter: CFTimeInterval = 0.0 ) {
            enabled ? (UIView.animate(withDuration: duration, //Time duration you want,
                delay: 0.0,
                options: [.curveEaseInOut, .autoreverse, .repeat],
                animations: { [weak self] in self?.alpha = 0.0 },
                completion: { [weak self] _ in self?.alpha = 1.0 })) : self.layer.removeAllAnimations()
            if !stopAfter.isEqual(to: 0.0) && enabled {
                DispatchQueue.main.asyncAfter(deadline: .now() + stopAfter) { [weak self] in
                    self?.layer.removeAllAnimations()
                }
            }
        }
    }
    

    First of all, I've overrided the hittest function to enabling the touch also when the button have the alpha equals to 0.0 (transparent) during the animation.

    Then , all input vars have a default value so you can launch the blink() method without parameters

    I've introduced also the enabled parameter to start or stop the animations on your button.

    Finally, if you want you can stop animation after a specific time with the stopAfter parameter.

    Usage:

    yourButton.blink() // infinite blink effect with the default duration of 1 second
    
    yourButton.blink(enabled:false) // stop the animation
    
    yourButton.blink(duration: 2.0) // slowly the animation to 2 seconds
    
    yourButton.blink(stopAfter:5.0) // the animation stops after 5 seconds.
    

    Typical uses:

    yourButton.blink(duration: 1.5, stopAfter:10.0)
    // your code..
    yourButton.blink()
    // other code..
    yourButton.blink(enabled:false)
    

提交回复
热议问题