Search code examples
iosswiftuibutton

How to make a button flash or blink?


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

func flashBG(){
    UIView.animateWithDuration(0.7, animations: {
        self.view.backgroundColor = UIColor.greenColor()

    })
}

But with a button it stays green

func flashBtn(){
    UIButton.animateWithDuration(0.5, animations: {
        self.buttonScan.backgroundColor = UIColor.greenColor()
    })
}

I have created the button by code

func setupScanButton() {
    let X_Co = (self.view.frame.size.width - 100)/2
    let Y_Co = (self.viewForLayer.frame.size.height + 36/2)

    buttonScan.frame = CGRectMake(X_Co,Y_Co,100,100)
    buttonScan.layer.borderColor = UIColor.whiteColor().CGColor
    buttonScan.layer.borderWidth = 2
    buttonScan.layer.cornerRadius = 50
    buttonScan.setTitle("Scan", forState: .Normal)
    buttonScan.backgroundColor = UIColor.blueColor()
    buttonScan.addTarget(self, action: "buttonScanAction", forControlEvents: .TouchUpInside)
    buttonScan.setTitleColor(UIColor(red:255/255, green: 255/255, blue:255/255, alpha: 1), forState: UIControlState.Normal)

    self.view.addSubview(buttonScan)
}

Should i call setupScanButton() again?


Solution

  • I hope that will solve your problem.

    buttonScan.alpha = 1.0
    UIView.animate(withDuration: 1.0, delay: 1.0, options: UIView.AnimationOptions.curveEaseOut, animations: {
    
        buttonScan.alpha = 0.0
    
    }, completion: nil)