How to make a button flash or blink?

前端 未结 12 1178
不思量自难忘°
不思量自难忘° 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 06:51

    This will start and stop a flashing button onClick, if you only want to flash the button immediately just use the first statement.

    var flashing = false
    
    @IBAction func btnFlash_Clicked(sender: AnyObject) {
            if !flashing{
                self.buttonScan.alpha = 1.0
                UIView.animateWithDuration(0.5, delay: 0.0, options: [.CurveEaseInOut, .Repeat, .Autoreverse, .AllowUserInteraction], animations: {() -> Void in
                    self.buttonScan.alpha = 0.0
                    }, completion: {(finished: Bool) -> Void in
                })
    
                flashing = true
            }
        else{
            UIView.animateWithDuration(0.1, delay: 0.0, options: [.CurveEaseInOut, .BeginFromCurrentState], animations: {() -> Void in
                self.buttonScan.alpha = 1.0
                }, completion: {(finished: Bool) -> Void in
            })
        }
    }
    

    Swift 5.x version

    An updated version with extension.

    extension UIView {
        func blink(duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, alpha: CGFloat = 0.0) {
            UIView.animate(withDuration: duration, delay: delay, options: [.curveEaseInOut, .repeat, .autoreverse], animations: {
                self.alpha = alpha
            })
        }
    }
    

    To call the function:

    button.blink() // without parameters
    button.blink(duration: 1, delay: 0.1, alpha: 0.2) // with parameters
    

提交回复
热议问题