How to make a button flash or blink?

前端 未结 12 1200
不思量自难忘°
不思量自难忘° 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条回答
  •  萌比男神i
    2021-02-01 06:56

    This UIView extension "blinks" a view and changes the background colour:

    /**
     Blinks a view with a given duration and optional color.
    
     - Parameter duration: The duration of the blink.
     - Parameter color: The color of the blink.
     */
    public func blink(withDuration duration: Double = 0.25, color: UIColor? = nil) {
    
        alpha = 0.2
        UIView.animate(withDuration: duration, delay: 0.0, options: [.curveEaseInOut], animations: {
            self.alpha = 1.0
        })
    
        guard let newBackgroundColor = color else { return }
        let oldBackgroundColor = backgroundColor
    
        UIView.animate(withDuration: duration, delay: 0.0, options: [.curveEaseInOut], animations: {
            self.backgroundColor = newBackgroundColor
            self.backgroundColor = oldBackgroundColor
        })
    
    }
    

    You would then use as follows:

    buttonScan.blink(color: .green)
    

提交回复
热议问题