Swift make background color flash or blink 2 random colors every time the button is pressed

Viewed 376

This app currently starts out with a black screen and when the button in the middle is pressed it change the background color every time the button is pressed. But I want the app to blink or flash 2 different colors: not just show one color that is not flashing.

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/12, delay:0, options:[ ], animations: {
            self.view.backgroundColor = self.colors.randomElement()
            self.view.backgroundColor = self.colors.randomElement()
        }, completion: nil)
    }
}
2 Answers

Try below

UIView.animate(withDuration: 1.0, delay: 0, options: .curveEaseOut, animations: {
    self.view.backgroundColor = self.colors.randomElement()
}, completion: { finished in
   print("another animation! - 1")
    UIView.animate(withDuration: 1.0, delay: 0, options: .curveEaseOut, animations: {
        self.view.backgroundColor = self.colors.randomElement()
    }, completion: { finished in
      print("another animation! - 2")
    })
})

Edit 1

To make forever use below.

func showColor() {
    UIView.animate(withDuration: 1.0, delay: 0, options: .curveEaseOut, animations: {
        self.view.backgroundColor = self.colors.randomElement()
    }, completion: { finished in
       print("another animation! - 1")
       Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(showColorAgain), userInfo: nil, repeats: false)
    })
}

@objc func showColorAgain() {
    showColor()
}

Now to make your logic until next click, you can handle that inside zshowColorAgain` function.

func blink() {
    let colors: [UIColor] = [color1, color2, color3, color4...]
    runBlink(with: colors)
}

func runBlink(with colors: [UIColor]) {
    guard let color = colors.first else { return }
    
    UIView.animate(withDuration: 0.15, delay: 0, options: .curveLinear, animations: {
        self.backgroundColor = color
    }, completion: { finished in
        if finished {
            var nextColors = colors
            nextColors.removeFirst()
            self.runBlink(with: nextColors)
        }
    })
}
Related