How can I make the background blink or flash continuously until the button is pressed again, then it will flash or blink 2 new random colors

Viewed 131

How can I make the background color flash 2 new colors continuously every time the button is pressed? Right now it just shows 2 colors but they don't blink or flash continuously.

import UIKit

class ViewController: UIViewController {
    
    let colors: [UIColor] = [
        .systemYellow,
        .systemGreen,
        .systemPurple,
        .systemPink,
        .systemRed,
        .systemBlue,
        .systemOrange,
        .black,.gray
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .clear
    }
    
    @IBAction func didTapButton() {
        
        UIView.animate(withDuration: 1/2, delay: 0, options: .curveEaseOut, animations: {
            self.view.backgroundColor = self.colors.randomElement()
        }, completion: { finished in
            print("another animation! - 1")
            UIView.animate(withDuration: 1/2, delay: 0, options: .curveEaseOut, animations: {
                self.view.backgroundColor = self.colors.randomElement()
            }, completion: { finished in
                print("another animation! - 2")
            })
        })
    }
}
1 Answers

Something like this?

Screen starts black, but once button is tapped, screen transitions between random colors. After bring tapped again, screen transitions between 2 new random colors.

You can use the [.repeat, .autoreverse] options to repeat and reverse the color animation.

Then, because the button is a subview of the view that you are animating (user interaction for the view and its subviews are normally disabled during animations), you can add the .allowUserInteraction option to allow pressing the button again.

@IBAction func didTapButton() {
    let color1 = self.colors.randomElement()
    let color2 = self.colors.randomElement()
    
    self.view.layer.removeAllAnimations()
    self.view.backgroundColor = color1 /// set to color1
    UIView.animate(withDuration: 1, delay: 0, options: [.repeat, .autoreverse, .allowUserInteraction]) {
        self.view.backgroundColor = color2 /// now animate to color2, reverse, then repeat
    }
}
Related